rigid_body_bullet.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. /*************************************************************************/
  2. /* rigid_body_bullet.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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 "rigid_body_bullet.h"
  31. #include "btRayShape.h"
  32. #include "bullet_physics_server.h"
  33. #include "bullet_types_converter.h"
  34. #include "bullet_utilities.h"
  35. #include "godot_motion_state.h"
  36. #include "joint_bullet.h"
  37. #include <BulletCollision/CollisionDispatch/btGhostObject.h>
  38. #include <BulletCollision/CollisionShapes/btConvexPointCloudShape.h>
  39. #include <BulletDynamics/Dynamics/btRigidBody.h>
  40. #include <btBulletCollisionCommon.h>
  41. #include <assert.h>
  42. /**
  43. @author AndreaCatania
  44. */
  45. BulletPhysicsDirectBodyState *BulletPhysicsDirectBodyState::singleton = nullptr;
  46. Vector3 BulletPhysicsDirectBodyState::get_total_gravity() const {
  47. Vector3 gVec;
  48. B_TO_G(body->btBody->getGravity(), gVec);
  49. return gVec;
  50. }
  51. float BulletPhysicsDirectBodyState::get_total_angular_damp() const {
  52. return body->btBody->getAngularDamping();
  53. }
  54. float BulletPhysicsDirectBodyState::get_total_linear_damp() const {
  55. return body->btBody->getLinearDamping();
  56. }
  57. Vector3 BulletPhysicsDirectBodyState::get_center_of_mass() const {
  58. Vector3 gVec;
  59. B_TO_G(body->btBody->getCenterOfMassPosition(), gVec);
  60. return gVec;
  61. }
  62. Basis BulletPhysicsDirectBodyState::get_principal_inertia_axes() const {
  63. return Basis();
  64. }
  65. float BulletPhysicsDirectBodyState::get_inverse_mass() const {
  66. return body->btBody->getInvMass();
  67. }
  68. Vector3 BulletPhysicsDirectBodyState::get_inverse_inertia() const {
  69. Vector3 gVec;
  70. B_TO_G(body->btBody->getInvInertiaDiagLocal(), gVec);
  71. return gVec;
  72. }
  73. Basis BulletPhysicsDirectBodyState::get_inverse_inertia_tensor() const {
  74. Basis gInertia;
  75. B_TO_G(body->btBody->getInvInertiaTensorWorld(), gInertia);
  76. return gInertia;
  77. }
  78. void BulletPhysicsDirectBodyState::set_linear_velocity(const Vector3 &p_velocity) {
  79. body->set_linear_velocity(p_velocity);
  80. }
  81. Vector3 BulletPhysicsDirectBodyState::get_linear_velocity() const {
  82. return body->get_linear_velocity();
  83. }
  84. void BulletPhysicsDirectBodyState::set_angular_velocity(const Vector3 &p_velocity) {
  85. body->set_angular_velocity(p_velocity);
  86. }
  87. Vector3 BulletPhysicsDirectBodyState::get_angular_velocity() const {
  88. return body->get_angular_velocity();
  89. }
  90. void BulletPhysicsDirectBodyState::set_transform(const Transform &p_transform) {
  91. body->set_transform(p_transform);
  92. }
  93. Transform BulletPhysicsDirectBodyState::get_transform() const {
  94. return body->get_transform();
  95. }
  96. Vector3 BulletPhysicsDirectBodyState::get_velocity_at_local_position(const Vector3 &p_position) const {
  97. btVector3 local_position;
  98. G_TO_B(p_position, local_position);
  99. Vector3 velocity;
  100. B_TO_G(body->btBody->getVelocityInLocalPoint(local_position), velocity);
  101. return velocity;
  102. }
  103. void BulletPhysicsDirectBodyState::add_central_force(const Vector3 &p_force) {
  104. body->apply_central_force(p_force);
  105. }
  106. void BulletPhysicsDirectBodyState::add_force(const Vector3 &p_force, const Vector3 &p_pos) {
  107. body->apply_force(p_force, p_pos);
  108. }
  109. void BulletPhysicsDirectBodyState::add_torque(const Vector3 &p_torque) {
  110. body->apply_torque(p_torque);
  111. }
  112. void BulletPhysicsDirectBodyState::apply_central_impulse(const Vector3 &p_impulse) {
  113. body->apply_central_impulse(p_impulse);
  114. }
  115. void BulletPhysicsDirectBodyState::apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse) {
  116. body->apply_impulse(p_pos, p_impulse);
  117. }
  118. void BulletPhysicsDirectBodyState::apply_torque_impulse(const Vector3 &p_impulse) {
  119. body->apply_torque_impulse(p_impulse);
  120. }
  121. void BulletPhysicsDirectBodyState::set_sleep_state(bool p_enable) {
  122. body->set_activation_state(p_enable);
  123. }
  124. bool BulletPhysicsDirectBodyState::is_sleeping() const {
  125. return !body->is_active();
  126. }
  127. int BulletPhysicsDirectBodyState::get_contact_count() const {
  128. return body->collisionsCount;
  129. }
  130. Vector3 BulletPhysicsDirectBodyState::get_contact_local_position(int p_contact_idx) const {
  131. return body->collisions[p_contact_idx].hitLocalLocation;
  132. }
  133. Vector3 BulletPhysicsDirectBodyState::get_contact_local_normal(int p_contact_idx) const {
  134. return body->collisions[p_contact_idx].hitNormal;
  135. }
  136. float BulletPhysicsDirectBodyState::get_contact_impulse(int p_contact_idx) const {
  137. return body->collisions[p_contact_idx].appliedImpulse;
  138. }
  139. int BulletPhysicsDirectBodyState::get_contact_local_shape(int p_contact_idx) const {
  140. return body->collisions[p_contact_idx].local_shape;
  141. }
  142. RID BulletPhysicsDirectBodyState::get_contact_collider(int p_contact_idx) const {
  143. return body->collisions[p_contact_idx].otherObject->get_self();
  144. }
  145. Vector3 BulletPhysicsDirectBodyState::get_contact_collider_position(int p_contact_idx) const {
  146. return body->collisions[p_contact_idx].hitWorldLocation;
  147. }
  148. ObjectID BulletPhysicsDirectBodyState::get_contact_collider_id(int p_contact_idx) const {
  149. return body->collisions[p_contact_idx].otherObject->get_instance_id();
  150. }
  151. int BulletPhysicsDirectBodyState::get_contact_collider_shape(int p_contact_idx) const {
  152. return body->collisions[p_contact_idx].other_object_shape;
  153. }
  154. Vector3 BulletPhysicsDirectBodyState::get_contact_collider_velocity_at_position(int p_contact_idx) const {
  155. RigidBodyBullet::CollisionData &colDat = body->collisions.write[p_contact_idx];
  156. btVector3 hitLocation;
  157. G_TO_B(colDat.hitLocalLocation, hitLocation);
  158. Vector3 velocityAtPoint;
  159. B_TO_G(colDat.otherObject->get_bt_rigid_body()->getVelocityInLocalPoint(hitLocation), velocityAtPoint);
  160. return velocityAtPoint;
  161. }
  162. PhysicsDirectSpaceState *BulletPhysicsDirectBodyState::get_space_state() {
  163. return body->get_space()->get_direct_state();
  164. }
  165. RigidBodyBullet::KinematicUtilities::KinematicUtilities(RigidBodyBullet *p_owner) :
  166. owner(p_owner),
  167. safe_margin(0.001) {
  168. }
  169. RigidBodyBullet::KinematicUtilities::~KinematicUtilities() {
  170. just_delete_shapes(shapes.size()); // don't need to resize
  171. }
  172. void RigidBodyBullet::KinematicUtilities::setSafeMargin(btScalar p_margin) {
  173. safe_margin = p_margin;
  174. copyAllOwnerShapes();
  175. }
  176. void RigidBodyBullet::KinematicUtilities::copyAllOwnerShapes() {
  177. const Vector<CollisionObjectBullet::ShapeWrapper> &shapes_wrappers(owner->get_shapes_wrappers());
  178. const int shapes_count = shapes_wrappers.size();
  179. just_delete_shapes(shapes_count);
  180. const CollisionObjectBullet::ShapeWrapper *shape_wrapper;
  181. btVector3 owner_scale(owner->get_bt_body_scale());
  182. for (int i = shapes_count - 1; 0 <= i; --i) {
  183. shape_wrapper = &shapes_wrappers[i];
  184. if (!shape_wrapper->active) {
  185. continue;
  186. }
  187. shapes.write[i].transform = shape_wrapper->transform;
  188. shapes.write[i].transform.getOrigin() *= owner_scale;
  189. switch (shape_wrapper->shape->get_type()) {
  190. case PhysicsServer::SHAPE_SPHERE:
  191. case PhysicsServer::SHAPE_BOX:
  192. case PhysicsServer::SHAPE_CAPSULE:
  193. case PhysicsServer::SHAPE_CYLINDER:
  194. case PhysicsServer::SHAPE_CONVEX_POLYGON:
  195. case PhysicsServer::SHAPE_RAY: {
  196. shapes.write[i].shape = static_cast<btConvexShape *>(shape_wrapper->shape->create_bt_shape(owner_scale * shape_wrapper->scale, safe_margin));
  197. } break;
  198. default:
  199. WARN_PRINT("This shape is not supported to be kinematic!");
  200. shapes.write[i].shape = nullptr;
  201. }
  202. }
  203. }
  204. void RigidBodyBullet::KinematicUtilities::just_delete_shapes(int new_size) {
  205. for (int i = shapes.size() - 1; 0 <= i; --i) {
  206. if (shapes[i].shape) {
  207. bulletdelete(shapes.write[i].shape);
  208. }
  209. }
  210. shapes.resize(new_size);
  211. }
  212. RigidBodyBullet::RigidBodyBullet() :
  213. RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_RIGID_BODY),
  214. kinematic_utilities(nullptr),
  215. locked_axis(0),
  216. mass(1),
  217. gravity_scale(1),
  218. linearDamp(0),
  219. angularDamp(0),
  220. can_sleep(true),
  221. omit_forces_integration(false),
  222. can_integrate_forces(false),
  223. maxCollisionsDetection(0),
  224. collisionsCount(0),
  225. prev_collision_count(0),
  226. maxAreasWhereIam(10),
  227. areaWhereIamCount(0),
  228. countGravityPointSpaces(0),
  229. isScratchedSpaceOverrideModificator(false),
  230. previousActiveState(true),
  231. force_integration_callback(nullptr) {
  232. godotMotionState = bulletnew(GodotMotionState(this));
  233. // Initial properties
  234. const btVector3 localInertia(0, 0, 0);
  235. btRigidBody::btRigidBodyConstructionInfo cInfo(mass, godotMotionState, nullptr, localInertia);
  236. btBody = bulletnew(btRigidBody(cInfo));
  237. reload_shapes();
  238. setupBulletCollisionObject(btBody);
  239. set_mode(PhysicsServer::BODY_MODE_RIGID);
  240. reload_axis_lock();
  241. areasWhereIam.resize(maxAreasWhereIam);
  242. for (int i = areasWhereIam.size() - 1; 0 <= i; --i) {
  243. areasWhereIam.write[i] = NULL;
  244. }
  245. btBody->setSleepingThresholds(0.2, 0.2);
  246. prev_collision_traces = &collision_traces_1;
  247. curr_collision_traces = &collision_traces_2;
  248. }
  249. RigidBodyBullet::~RigidBodyBullet() {
  250. bulletdelete(godotMotionState);
  251. if (force_integration_callback) {
  252. memdelete(force_integration_callback);
  253. }
  254. destroy_kinematic_utilities();
  255. }
  256. void RigidBodyBullet::init_kinematic_utilities() {
  257. kinematic_utilities = memnew(KinematicUtilities(this));
  258. reload_kinematic_shapes();
  259. }
  260. void RigidBodyBullet::destroy_kinematic_utilities() {
  261. if (kinematic_utilities) {
  262. memdelete(kinematic_utilities);
  263. kinematic_utilities = nullptr;
  264. }
  265. }
  266. void RigidBodyBullet::main_shape_changed() {
  267. CRASH_COND(!get_main_shape());
  268. btBody->setCollisionShape(get_main_shape());
  269. set_continuous_collision_detection(is_continuous_collision_detection_enabled()); // Reset
  270. }
  271. void RigidBodyBullet::reload_body() {
  272. if (space) {
  273. space->remove_rigid_body(this);
  274. if (get_main_shape()) {
  275. space->add_rigid_body(this);
  276. }
  277. }
  278. }
  279. void RigidBodyBullet::set_space(SpaceBullet *p_space) {
  280. // Clear the old space if there is one
  281. if (space) {
  282. can_integrate_forces = false;
  283. isScratchedSpaceOverrideModificator = false;
  284. // Remove any constraints
  285. space->remove_rigid_body_constraints(this);
  286. // Remove this object form the physics world
  287. space->remove_rigid_body(this);
  288. }
  289. space = p_space;
  290. if (space) {
  291. space->add_rigid_body(this);
  292. }
  293. }
  294. void RigidBodyBullet::dispatch_callbacks() {
  295. /// The check isFirstTransformChanged is necessary in order to call integrated forces only when the first transform is sent
  296. if ((btBody->isKinematicObject() || btBody->isActive() || previousActiveState != btBody->isActive()) && force_integration_callback && can_integrate_forces) {
  297. if (omit_forces_integration) {
  298. btBody->clearForces();
  299. }
  300. BulletPhysicsDirectBodyState *bodyDirect = BulletPhysicsDirectBodyState::get_singleton(this);
  301. Variant variantBodyDirect = bodyDirect;
  302. Object *obj = ObjectDB::get_instance(force_integration_callback->id);
  303. if (!obj) {
  304. // Remove integration callback
  305. set_force_integration_callback(0, StringName());
  306. } else {
  307. const Variant *vp[2] = { &variantBodyDirect, &force_integration_callback->udata };
  308. Variant::CallError responseCallError;
  309. int argc = (force_integration_callback->udata.get_type() == Variant::NIL) ? 1 : 2;
  310. obj->call(force_integration_callback->method, vp, argc, responseCallError);
  311. }
  312. }
  313. if (isScratchedSpaceOverrideModificator || 0 < countGravityPointSpaces) {
  314. isScratchedSpaceOverrideModificator = false;
  315. reload_space_override_modificator();
  316. }
  317. /// Lock axis
  318. btBody->setLinearVelocity(btBody->getLinearVelocity() * btBody->getLinearFactor());
  319. btBody->setAngularVelocity(btBody->getAngularVelocity() * btBody->getAngularFactor());
  320. previousActiveState = btBody->isActive();
  321. }
  322. void RigidBodyBullet::set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata) {
  323. if (force_integration_callback) {
  324. memdelete(force_integration_callback);
  325. force_integration_callback = nullptr;
  326. }
  327. if (p_id != 0) {
  328. force_integration_callback = memnew(ForceIntegrationCallback);
  329. force_integration_callback->id = p_id;
  330. force_integration_callback->method = p_method;
  331. force_integration_callback->udata = p_udata;
  332. }
  333. }
  334. void RigidBodyBullet::scratch_space_override_modificator() {
  335. isScratchedSpaceOverrideModificator = true;
  336. }
  337. void RigidBodyBullet::on_collision_filters_change() {
  338. if (space) {
  339. space->reload_collision_filters(this);
  340. }
  341. set_activation_state(true);
  342. }
  343. void RigidBodyBullet::on_collision_checker_start() {
  344. prev_collision_count = collisionsCount;
  345. collisionsCount = 0;
  346. // Swap array
  347. Vector<RigidBodyBullet *> *s = prev_collision_traces;
  348. prev_collision_traces = curr_collision_traces;
  349. curr_collision_traces = s;
  350. }
  351. void RigidBodyBullet::on_collision_checker_end() {
  352. // Always true if active and not a static or kinematic body
  353. isTransformChanged = btBody->isActive() && !btBody->isStaticOrKinematicObject();
  354. }
  355. bool RigidBodyBullet::add_collision_object(RigidBodyBullet *p_otherObject, const Vector3 &p_hitWorldLocation, const Vector3 &p_hitLocalLocation, const Vector3 &p_hitNormal, const float &p_appliedImpulse, int p_other_shape_index, int p_local_shape_index) {
  356. if (collisionsCount >= maxCollisionsDetection) {
  357. return false;
  358. }
  359. CollisionData &cd = collisions.write[collisionsCount];
  360. cd.hitLocalLocation = p_hitLocalLocation;
  361. cd.otherObject = p_otherObject;
  362. cd.hitWorldLocation = p_hitWorldLocation;
  363. cd.hitNormal = p_hitNormal;
  364. cd.appliedImpulse = p_appliedImpulse;
  365. cd.other_object_shape = p_other_shape_index;
  366. cd.local_shape = p_local_shape_index;
  367. curr_collision_traces->write[collisionsCount] = p_otherObject;
  368. ++collisionsCount;
  369. return true;
  370. }
  371. bool RigidBodyBullet::was_colliding(RigidBodyBullet *p_other_object) {
  372. for (int i = prev_collision_count - 1; 0 <= i; --i) {
  373. if ((*prev_collision_traces)[i] == p_other_object) {
  374. return true;
  375. }
  376. }
  377. return false;
  378. }
  379. void RigidBodyBullet::set_activation_state(bool p_active) {
  380. if (p_active) {
  381. btBody->activate();
  382. } else {
  383. btBody->setActivationState(WANTS_DEACTIVATION);
  384. }
  385. }
  386. bool RigidBodyBullet::is_active() const {
  387. return btBody->isActive();
  388. }
  389. void RigidBodyBullet::set_omit_forces_integration(bool p_omit) {
  390. omit_forces_integration = p_omit;
  391. }
  392. void RigidBodyBullet::set_param(PhysicsServer::BodyParameter p_param, real_t p_value) {
  393. switch (p_param) {
  394. case PhysicsServer::BODY_PARAM_BOUNCE:
  395. btBody->setRestitution(p_value);
  396. break;
  397. case PhysicsServer::BODY_PARAM_FRICTION:
  398. btBody->setFriction(p_value);
  399. break;
  400. case PhysicsServer::BODY_PARAM_MASS: {
  401. ERR_FAIL_COND(p_value < 0);
  402. mass = p_value;
  403. _internal_set_mass(p_value);
  404. break;
  405. }
  406. case PhysicsServer::BODY_PARAM_LINEAR_DAMP:
  407. linearDamp = p_value;
  408. // Mark for updating total linear damping.
  409. scratch_space_override_modificator();
  410. break;
  411. case PhysicsServer::BODY_PARAM_ANGULAR_DAMP:
  412. angularDamp = p_value;
  413. // Mark for updating total angular damping.
  414. scratch_space_override_modificator();
  415. break;
  416. case PhysicsServer::BODY_PARAM_GRAVITY_SCALE:
  417. gravity_scale = p_value;
  418. // The Bullet gravity will be is set by reload_space_override_modificator.
  419. // Mark for updating total gravity scale.
  420. scratch_space_override_modificator();
  421. break;
  422. default:
  423. WARN_PRINT("Parameter " + itos(p_param) + " not supported by bullet. Value: " + itos(p_value));
  424. }
  425. }
  426. real_t RigidBodyBullet::get_param(PhysicsServer::BodyParameter p_param) const {
  427. switch (p_param) {
  428. case PhysicsServer::BODY_PARAM_BOUNCE:
  429. return btBody->getRestitution();
  430. case PhysicsServer::BODY_PARAM_FRICTION:
  431. return btBody->getFriction();
  432. case PhysicsServer::BODY_PARAM_MASS: {
  433. const btScalar invMass = btBody->getInvMass();
  434. return 0 == invMass ? 0 : 1 / invMass;
  435. }
  436. case PhysicsServer::BODY_PARAM_LINEAR_DAMP:
  437. return linearDamp;
  438. case PhysicsServer::BODY_PARAM_ANGULAR_DAMP:
  439. return angularDamp;
  440. case PhysicsServer::BODY_PARAM_GRAVITY_SCALE:
  441. return gravity_scale;
  442. default:
  443. WARN_PRINT("Parameter " + itos(p_param) + " not supported by bullet");
  444. return 0;
  445. }
  446. }
  447. void RigidBodyBullet::set_mode(PhysicsServer::BodyMode p_mode) {
  448. // This is necessary to block force_integration untile next move
  449. can_integrate_forces = false;
  450. destroy_kinematic_utilities();
  451. // The mode change is relevant to its mass
  452. switch (p_mode) {
  453. case PhysicsServer::BODY_MODE_KINEMATIC:
  454. mode = PhysicsServer::BODY_MODE_KINEMATIC;
  455. reload_axis_lock();
  456. _internal_set_mass(0);
  457. init_kinematic_utilities();
  458. break;
  459. case PhysicsServer::BODY_MODE_STATIC:
  460. mode = PhysicsServer::BODY_MODE_STATIC;
  461. reload_axis_lock();
  462. _internal_set_mass(0);
  463. break;
  464. case PhysicsServer::BODY_MODE_RIGID:
  465. mode = PhysicsServer::BODY_MODE_RIGID;
  466. reload_axis_lock();
  467. _internal_set_mass(0 == mass ? 1 : mass);
  468. scratch_space_override_modificator();
  469. break;
  470. case PhysicsServer::BODY_MODE_CHARACTER:
  471. mode = PhysicsServer::BODY_MODE_CHARACTER;
  472. reload_axis_lock();
  473. _internal_set_mass(0 == mass ? 1 : mass);
  474. scratch_space_override_modificator();
  475. break;
  476. }
  477. btBody->setAngularVelocity(btVector3(0, 0, 0));
  478. btBody->setLinearVelocity(btVector3(0, 0, 0));
  479. }
  480. PhysicsServer::BodyMode RigidBodyBullet::get_mode() const {
  481. return mode;
  482. }
  483. void RigidBodyBullet::set_state(PhysicsServer::BodyState p_state, const Variant &p_variant) {
  484. switch (p_state) {
  485. case PhysicsServer::BODY_STATE_TRANSFORM:
  486. set_transform(p_variant);
  487. break;
  488. case PhysicsServer::BODY_STATE_LINEAR_VELOCITY:
  489. set_linear_velocity(p_variant);
  490. break;
  491. case PhysicsServer::BODY_STATE_ANGULAR_VELOCITY:
  492. set_angular_velocity(p_variant);
  493. break;
  494. case PhysicsServer::BODY_STATE_SLEEPING:
  495. set_activation_state(!bool(p_variant));
  496. break;
  497. case PhysicsServer::BODY_STATE_CAN_SLEEP:
  498. can_sleep = bool(p_variant);
  499. if (!can_sleep) {
  500. // Can't sleep
  501. btBody->forceActivationState(DISABLE_DEACTIVATION);
  502. } else {
  503. btBody->forceActivationState(ACTIVE_TAG);
  504. }
  505. break;
  506. }
  507. }
  508. Variant RigidBodyBullet::get_state(PhysicsServer::BodyState p_state) const {
  509. switch (p_state) {
  510. case PhysicsServer::BODY_STATE_TRANSFORM:
  511. return get_transform();
  512. case PhysicsServer::BODY_STATE_LINEAR_VELOCITY:
  513. return get_linear_velocity();
  514. case PhysicsServer::BODY_STATE_ANGULAR_VELOCITY:
  515. return get_angular_velocity();
  516. case PhysicsServer::BODY_STATE_SLEEPING:
  517. return !is_active();
  518. case PhysicsServer::BODY_STATE_CAN_SLEEP:
  519. return can_sleep;
  520. default:
  521. WARN_PRINT("This state " + itos(p_state) + " is not supported by Bullet");
  522. return Variant();
  523. }
  524. }
  525. void RigidBodyBullet::apply_central_impulse(const Vector3 &p_impulse) {
  526. btVector3 btImpu;
  527. G_TO_B(p_impulse, btImpu);
  528. if (Vector3() != p_impulse) {
  529. btBody->activate();
  530. }
  531. btBody->applyCentralImpulse(btImpu);
  532. }
  533. void RigidBodyBullet::apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse) {
  534. btVector3 btImpu;
  535. btVector3 btPos;
  536. G_TO_B(p_impulse, btImpu);
  537. G_TO_B(p_pos, btPos);
  538. if (Vector3() != p_impulse) {
  539. btBody->activate();
  540. }
  541. btBody->applyImpulse(btImpu, btPos);
  542. }
  543. void RigidBodyBullet::apply_torque_impulse(const Vector3 &p_impulse) {
  544. btVector3 btImp;
  545. G_TO_B(p_impulse, btImp);
  546. if (Vector3() != p_impulse) {
  547. btBody->activate();
  548. }
  549. btBody->applyTorqueImpulse(btImp);
  550. }
  551. void RigidBodyBullet::apply_force(const Vector3 &p_force, const Vector3 &p_pos) {
  552. btVector3 btForce;
  553. btVector3 btPos;
  554. G_TO_B(p_force, btForce);
  555. G_TO_B(p_pos, btPos);
  556. if (Vector3() != p_force) {
  557. btBody->activate();
  558. }
  559. btBody->applyForce(btForce, btPos);
  560. }
  561. void RigidBodyBullet::apply_central_force(const Vector3 &p_force) {
  562. btVector3 btForce;
  563. G_TO_B(p_force, btForce);
  564. if (Vector3() != p_force) {
  565. btBody->activate();
  566. }
  567. btBody->applyCentralForce(btForce);
  568. }
  569. void RigidBodyBullet::apply_torque(const Vector3 &p_torque) {
  570. btVector3 btTorq;
  571. G_TO_B(p_torque, btTorq);
  572. if (Vector3() != p_torque) {
  573. btBody->activate();
  574. }
  575. btBody->applyTorque(btTorq);
  576. }
  577. void RigidBodyBullet::set_applied_force(const Vector3 &p_force) {
  578. btVector3 btVec = btBody->getTotalTorque();
  579. if (Vector3() != p_force) {
  580. btBody->activate();
  581. }
  582. btBody->clearForces();
  583. btBody->applyTorque(btVec);
  584. G_TO_B(p_force, btVec);
  585. btBody->applyCentralForce(btVec);
  586. }
  587. Vector3 RigidBodyBullet::get_applied_force() const {
  588. Vector3 gTotForc;
  589. B_TO_G(btBody->getTotalForce(), gTotForc);
  590. return gTotForc;
  591. }
  592. void RigidBodyBullet::set_applied_torque(const Vector3 &p_torque) {
  593. btVector3 btVec = btBody->getTotalForce();
  594. if (Vector3() != p_torque) {
  595. btBody->activate();
  596. }
  597. btBody->clearForces();
  598. btBody->applyCentralForce(btVec);
  599. G_TO_B(p_torque, btVec);
  600. btBody->applyTorque(btVec);
  601. }
  602. Vector3 RigidBodyBullet::get_applied_torque() const {
  603. Vector3 gTotTorq;
  604. B_TO_G(btBody->getTotalTorque(), gTotTorq);
  605. return gTotTorq;
  606. }
  607. void RigidBodyBullet::set_axis_lock(PhysicsServer::BodyAxis p_axis, bool lock) {
  608. if (lock) {
  609. locked_axis |= p_axis;
  610. } else {
  611. locked_axis &= ~p_axis;
  612. }
  613. reload_axis_lock();
  614. }
  615. bool RigidBodyBullet::is_axis_locked(PhysicsServer::BodyAxis p_axis) const {
  616. return locked_axis & p_axis;
  617. }
  618. void RigidBodyBullet::reload_axis_lock() {
  619. btBody->setLinearFactor(btVector3(float(!is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_X)), float(!is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_Y)), float(!is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_Z))));
  620. if (PhysicsServer::BODY_MODE_CHARACTER == mode) {
  621. /// When character angular is always locked
  622. btBody->setAngularFactor(btVector3(0., 0., 0.));
  623. } else {
  624. btBody->setAngularFactor(btVector3(float(!is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_X)), float(!is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_Y)), float(!is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_Z))));
  625. }
  626. }
  627. void RigidBodyBullet::set_continuous_collision_detection(bool p_enable) {
  628. if (p_enable) {
  629. // This threshold enable CCD if the object moves more than
  630. // 1 meter in one simulation frame
  631. btBody->setCcdMotionThreshold(1e-7);
  632. /// Calculate using the rule writte below the CCD swept sphere radius
  633. /// CCD works on an embedded sphere of radius, make sure this radius
  634. /// is embedded inside the convex objects, preferably smaller:
  635. /// for an object of dimensions 1 meter, try 0.2
  636. btScalar radius(1.0);
  637. if (btBody->getCollisionShape()) {
  638. btVector3 center;
  639. btBody->getCollisionShape()->getBoundingSphere(center, radius);
  640. }
  641. btBody->setCcdSweptSphereRadius(radius * 0.2);
  642. } else {
  643. btBody->setCcdMotionThreshold(10000.0);
  644. btBody->setCcdSweptSphereRadius(0.);
  645. }
  646. }
  647. bool RigidBodyBullet::is_continuous_collision_detection_enabled() const {
  648. return 0. < btBody->getCcdMotionThreshold();
  649. }
  650. void RigidBodyBullet::set_linear_velocity(const Vector3 &p_velocity) {
  651. btVector3 btVec;
  652. G_TO_B(p_velocity, btVec);
  653. if (Vector3() != p_velocity) {
  654. btBody->activate();
  655. }
  656. btBody->setLinearVelocity(btVec);
  657. }
  658. Vector3 RigidBodyBullet::get_linear_velocity() const {
  659. Vector3 gVec;
  660. B_TO_G(btBody->getLinearVelocity(), gVec);
  661. return gVec;
  662. }
  663. void RigidBodyBullet::set_angular_velocity(const Vector3 &p_velocity) {
  664. btVector3 btVec;
  665. G_TO_B(p_velocity, btVec);
  666. if (Vector3() != p_velocity) {
  667. btBody->activate();
  668. }
  669. btBody->setAngularVelocity(btVec);
  670. }
  671. Vector3 RigidBodyBullet::get_angular_velocity() const {
  672. Vector3 gVec;
  673. B_TO_G(btBody->getAngularVelocity(), gVec);
  674. return gVec;
  675. }
  676. void RigidBodyBullet::set_transform__bullet(const btTransform &p_global_transform) {
  677. if (mode == PhysicsServer::BODY_MODE_KINEMATIC) {
  678. if (space && space->get_delta_time() != 0) {
  679. btBody->setLinearVelocity((p_global_transform.getOrigin() - btBody->getWorldTransform().getOrigin()) / space->get_delta_time());
  680. }
  681. // The kinematic use MotionState class
  682. godotMotionState->moveBody(p_global_transform);
  683. } else {
  684. // Is necessary to avoid wrong location on the rendering side on the next frame
  685. godotMotionState->setWorldTransform(p_global_transform);
  686. }
  687. CollisionObjectBullet::set_transform__bullet(p_global_transform);
  688. }
  689. const btTransform &RigidBodyBullet::get_transform__bullet() const {
  690. if (is_static()) {
  691. return RigidCollisionObjectBullet::get_transform__bullet();
  692. } else {
  693. return godotMotionState->getCurrentWorldTransform();
  694. }
  695. }
  696. void RigidBodyBullet::reload_shapes() {
  697. RigidCollisionObjectBullet::reload_shapes();
  698. const btScalar invMass = btBody->getInvMass();
  699. const btScalar mass = invMass == 0 ? 0 : 1 / invMass;
  700. if (mainShape) {
  701. // inertia initialised zero here because some of bullet's collision
  702. // shapes incorrectly do not set the vector in calculateLocalIntertia.
  703. // Arbitrary zero is preferable to undefined behaviour.
  704. btVector3 inertia(0, 0, 0);
  705. if (EMPTY_SHAPE_PROXYTYPE != mainShape->getShapeType()) { // Necessary to avoid assertion of the empty shape
  706. mainShape->calculateLocalInertia(mass, inertia);
  707. }
  708. btBody->setMassProps(mass, inertia);
  709. }
  710. btBody->updateInertiaTensor();
  711. reload_kinematic_shapes();
  712. set_continuous_collision_detection(btBody->getCcdMotionThreshold() < 9998.0);
  713. reload_body();
  714. }
  715. void RigidBodyBullet::on_enter_area(AreaBullet *p_area) {
  716. /// Add this area to the array in an ordered way
  717. ++areaWhereIamCount;
  718. if (areaWhereIamCount >= maxAreasWhereIam) {
  719. --areaWhereIamCount;
  720. return;
  721. }
  722. for (int i = 0; i < areaWhereIamCount; ++i) {
  723. if (NULL == areasWhereIam[i]) {
  724. // This area has the highest priority
  725. areasWhereIam.write[i] = p_area;
  726. break;
  727. } else {
  728. if (areasWhereIam[i]->get_spOv_priority() > p_area->get_spOv_priority()) {
  729. // The position was found, just shift all elements
  730. for (int j = areaWhereIamCount; j > i; j--) {
  731. areasWhereIam.write[j] = areasWhereIam[j - 1];
  732. }
  733. areasWhereIam.write[i] = p_area;
  734. break;
  735. }
  736. }
  737. }
  738. if (PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED != p_area->get_spOv_mode()) {
  739. scratch_space_override_modificator();
  740. }
  741. if (p_area->is_spOv_gravityPoint()) {
  742. ++countGravityPointSpaces;
  743. ERR_FAIL_COND(countGravityPointSpaces <= 0);
  744. }
  745. }
  746. void RigidBodyBullet::on_exit_area(AreaBullet *p_area) {
  747. RigidCollisionObjectBullet::on_exit_area(p_area);
  748. /// Remove this area and keep the order
  749. /// N.B. Since I don't want resize the array I can't use the "erase" function
  750. bool wasTheAreaFound = false;
  751. for (int i = 0; i < areaWhereIamCount; ++i) {
  752. if (p_area == areasWhereIam[i]) {
  753. // The area was found, just shift down all elements
  754. for (int j = i; j < areaWhereIamCount; ++j) {
  755. areasWhereIam.write[j] = areasWhereIam[j + 1];
  756. }
  757. wasTheAreaFound = true;
  758. break;
  759. }
  760. }
  761. if (wasTheAreaFound) {
  762. if (p_area->is_spOv_gravityPoint()) {
  763. --countGravityPointSpaces;
  764. ERR_FAIL_COND(countGravityPointSpaces < 0);
  765. }
  766. --areaWhereIamCount;
  767. areasWhereIam.write[areaWhereIamCount] = NULL; // Even if this is not required, I clear the last element to be safe
  768. if (PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED != p_area->get_spOv_mode()) {
  769. scratch_space_override_modificator();
  770. }
  771. }
  772. }
  773. void RigidBodyBullet::reload_space_override_modificator() {
  774. if (mode == PhysicsServer::BODY_MODE_STATIC) {
  775. return;
  776. }
  777. Vector3 newGravity(0.0, 0.0, 0.0);
  778. real_t newLinearDamp = MAX(0.0, linearDamp);
  779. real_t newAngularDamp = MAX(0.0, angularDamp);
  780. AreaBullet *currentArea;
  781. // Variable used to calculate new gravity for gravity point areas, it is pointed by currentGravity pointer
  782. Vector3 support_gravity(0, 0, 0);
  783. bool stopped = false;
  784. for (int i = areaWhereIamCount - 1; (0 <= i) && !stopped; --i) {
  785. currentArea = areasWhereIam[i];
  786. if (!currentArea || PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED == currentArea->get_spOv_mode()) {
  787. continue;
  788. }
  789. /// Here is calculated the gravity
  790. if (currentArea->is_spOv_gravityPoint()) {
  791. /// It calculates the direction of new gravity
  792. support_gravity = currentArea->get_transform().xform(currentArea->get_spOv_gravityVec()) - get_transform().get_origin();
  793. real_t distanceMag = support_gravity.length();
  794. // Normalized in this way to avoid the double call of function "length()"
  795. if (distanceMag == 0) {
  796. support_gravity.x = 0;
  797. support_gravity.y = 0;
  798. support_gravity.z = 0;
  799. } else {
  800. support_gravity.x /= distanceMag;
  801. support_gravity.y /= distanceMag;
  802. support_gravity.z /= distanceMag;
  803. }
  804. /// Here is calculated the final gravity
  805. if (currentArea->get_spOv_gravityPointDistanceScale() > 0) {
  806. // Scaled gravity by distance
  807. support_gravity *= currentArea->get_spOv_gravityMag() / Math::pow(distanceMag * currentArea->get_spOv_gravityPointDistanceScale() + 1, 2);
  808. } else {
  809. // Unscaled gravity
  810. support_gravity *= currentArea->get_spOv_gravityMag();
  811. }
  812. } else {
  813. support_gravity = currentArea->get_spOv_gravityVec() * currentArea->get_spOv_gravityMag();
  814. }
  815. switch (currentArea->get_spOv_mode()) {
  816. case PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED:
  817. /// This area does not affect gravity/damp. These are generally areas
  818. /// that exist only to detect collisions, and objects entering or exiting them.
  819. break;
  820. case PhysicsServer::AREA_SPACE_OVERRIDE_COMBINE:
  821. /// This area adds its gravity/damp values to whatever has been
  822. /// calculated so far. This way, many overlapping areas can combine
  823. /// their physics to make interesting
  824. newGravity += support_gravity;
  825. newLinearDamp += currentArea->get_spOv_linearDamp();
  826. newAngularDamp += currentArea->get_spOv_angularDamp();
  827. break;
  828. case PhysicsServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE:
  829. /// This area adds its gravity/damp values to whatever has been calculated
  830. /// so far. Then stops taking into account the rest of the areas, even the
  831. /// default one.
  832. newGravity += support_gravity;
  833. newLinearDamp += currentArea->get_spOv_linearDamp();
  834. newAngularDamp += currentArea->get_spOv_angularDamp();
  835. stopped = true;
  836. break;
  837. case PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE:
  838. /// This area replaces any gravity/damp, even the default one, and
  839. /// stops taking into account the rest of the areas.
  840. newGravity = support_gravity;
  841. newLinearDamp = currentArea->get_spOv_linearDamp();
  842. newAngularDamp = currentArea->get_spOv_angularDamp();
  843. stopped = true;
  844. break;
  845. case PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE_COMBINE:
  846. /// This area replaces any gravity/damp calculated so far, but keeps
  847. /// calculating the rest of the areas, down to the default one.
  848. newGravity = support_gravity;
  849. newLinearDamp = currentArea->get_spOv_linearDamp();
  850. newAngularDamp = currentArea->get_spOv_angularDamp();
  851. break;
  852. }
  853. }
  854. // Add default gravity and damping from space.
  855. if (!stopped) {
  856. newGravity += space->get_gravity_direction() * space->get_gravity_magnitude();
  857. newLinearDamp += space->get_linear_damp();
  858. newAngularDamp += space->get_angular_damp();
  859. }
  860. btVector3 newBtGravity;
  861. G_TO_B(newGravity * gravity_scale, newBtGravity);
  862. btBody->setGravity(newBtGravity);
  863. btBody->setDamping(newLinearDamp, newAngularDamp);
  864. }
  865. void RigidBodyBullet::reload_kinematic_shapes() {
  866. if (!kinematic_utilities) {
  867. return;
  868. }
  869. kinematic_utilities->copyAllOwnerShapes();
  870. }
  871. void RigidBodyBullet::notify_transform_changed() {
  872. RigidCollisionObjectBullet::notify_transform_changed();
  873. can_integrate_forces = true;
  874. }
  875. void RigidBodyBullet::_internal_set_mass(real_t p_mass) {
  876. btVector3 localInertia(0, 0, 0);
  877. int clearedCurrentFlags = btBody->getCollisionFlags();
  878. clearedCurrentFlags &= ~(btCollisionObject::CF_KINEMATIC_OBJECT | btCollisionObject::CF_STATIC_OBJECT | btCollisionObject::CF_CHARACTER_OBJECT);
  879. // Rigidbody is dynamic if and only if mass is non Zero, otherwise static
  880. const bool isDynamic = p_mass != 0.f;
  881. if (isDynamic) {
  882. if (PhysicsServer::BODY_MODE_RIGID != mode && PhysicsServer::BODY_MODE_CHARACTER != mode) {
  883. return;
  884. }
  885. m_isStatic = false;
  886. if (mainShape) {
  887. mainShape->calculateLocalInertia(p_mass, localInertia);
  888. }
  889. if (PhysicsServer::BODY_MODE_RIGID == mode) {
  890. btBody->setCollisionFlags(clearedCurrentFlags); // Just set the flags without Kin and Static
  891. } else {
  892. btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_CHARACTER_OBJECT);
  893. }
  894. if (can_sleep) {
  895. btBody->forceActivationState(ACTIVE_TAG); // ACTIVE_TAG 1
  896. } else {
  897. btBody->forceActivationState(DISABLE_DEACTIVATION); // DISABLE_DEACTIVATION 4
  898. }
  899. } else {
  900. if (PhysicsServer::BODY_MODE_STATIC != mode && PhysicsServer::BODY_MODE_KINEMATIC != mode) {
  901. return;
  902. }
  903. m_isStatic = true;
  904. if (PhysicsServer::BODY_MODE_STATIC == mode) {
  905. btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_STATIC_OBJECT);
  906. } else {
  907. btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_KINEMATIC_OBJECT);
  908. set_transform__bullet(btBody->getWorldTransform()); // Set current Transform using kinematic method
  909. }
  910. btBody->forceActivationState(DISABLE_SIMULATION); // DISABLE_SIMULATION 5
  911. }
  912. btBody->setMassProps(p_mass, localInertia);
  913. btBody->updateInertiaTensor();
  914. reload_body();
  915. }