PhysicsRigidBody.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. #include "Base.h"
  2. #include "PhysicsRigidBody.h"
  3. #include "PhysicsController.h"
  4. #include "Game.h"
  5. #include "Image.h"
  6. #include "MeshPart.h"
  7. #include "Node.h"
  8. #include "Terrain.h"
  9. namespace gameplay
  10. {
  11. PhysicsRigidBody::PhysicsRigidBody(Node* node, const PhysicsCollisionShape::Definition& shape, const Parameters& parameters)
  12. : PhysicsCollisionObject(node), _body(NULL), _mass(parameters.mass), _constraints(NULL), _inDestructor(false)
  13. {
  14. GP_ASSERT(Game::getInstance()->getPhysicsController());
  15. GP_ASSERT(_node);
  16. // Create our collision shape.
  17. Vector3 centerOfMassOffset;
  18. _collisionShape = Game::getInstance()->getPhysicsController()->createShape(node, shape, &centerOfMassOffset);
  19. GP_ASSERT(_collisionShape && _collisionShape->getShape());
  20. // Create motion state object.
  21. _motionState = new PhysicsMotionState(node, this, (centerOfMassOffset.lengthSquared() > MATH_EPSILON) ? &centerOfMassOffset : NULL);
  22. // If the mass is non-zero, then the object is dynamic so we calculate the local
  23. // inertia. However, if the collision shape is a triangle mesh, we don't calculate
  24. // inertia since Bullet doesn't currently support this.
  25. btVector3 localInertia(0.0, 0.0, 0.0);
  26. if (parameters.mass != 0.0 && _collisionShape->getType() != PhysicsCollisionShape::SHAPE_MESH)
  27. _collisionShape->getShape()->calculateLocalInertia(parameters.mass, localInertia);
  28. // Create the Bullet physics rigid body object.
  29. btRigidBody::btRigidBodyConstructionInfo rbInfo(parameters.mass, NULL, _collisionShape->getShape(), localInertia);
  30. rbInfo.m_friction = parameters.friction;
  31. rbInfo.m_restitution = parameters.restitution;
  32. rbInfo.m_linearDamping = parameters.linearDamping;
  33. rbInfo.m_angularDamping = parameters.angularDamping;
  34. // Create + assign the new bullet rigid body object.
  35. _body = bullet_new<btRigidBody>(rbInfo);
  36. // Set motion state after rigid body assignment, since bullet will callback on the motion state interface to query
  37. // the initial transform and it will need to access to rigid body (_body).
  38. _body->setMotionState(_motionState);
  39. // Set other initially defined properties.
  40. setKinematic(parameters.kinematic);
  41. setAnisotropicFriction(parameters.anisotropicFriction);
  42. setAngularFactor(parameters.angularFactor);
  43. setLinearFactor(parameters.linearFactor);
  44. // Add ourself to the physics world.
  45. Game::getInstance()->getPhysicsController()->addCollisionObject(this);
  46. if (_collisionShape->getType() == PhysicsCollisionShape::SHAPE_HEIGHTFIELD)
  47. {
  48. // Add a listener on the node's transform so we can track dirty changes to calculate
  49. // an inverse matrix for transforming heightfield points between world and local space.
  50. _node->addListener(this);
  51. }
  52. }
  53. PhysicsRigidBody::~PhysicsRigidBody()
  54. {
  55. GP_ASSERT(Game::getInstance()->getPhysicsController());
  56. GP_ASSERT(_collisionShape);
  57. GP_ASSERT(_node);
  58. // Clean up all constraints linked to this rigid body.
  59. _inDestructor = true;
  60. if (_constraints)
  61. {
  62. for (unsigned int i = 0; i < _constraints->size(); ++i)
  63. {
  64. SAFE_DELETE((*_constraints)[i]);
  65. }
  66. SAFE_DELETE(_constraints);
  67. }
  68. // Remove collision object from physics controller.
  69. Game::getInstance()->getPhysicsController()->removeCollisionObject(this, true);
  70. // Clean up the rigid body and its related objects.
  71. SAFE_DELETE(_body);
  72. // Unregister node listener (only registered for heihgtfield collision shape types).
  73. if (_collisionShape->getType() == PhysicsCollisionShape::SHAPE_HEIGHTFIELD)
  74. {
  75. _node->removeListener(this);
  76. }
  77. }
  78. PhysicsCollisionObject::Type PhysicsRigidBody::getType() const
  79. {
  80. return PhysicsCollisionObject::RIGID_BODY;
  81. }
  82. btCollisionObject* PhysicsRigidBody::getCollisionObject() const
  83. {
  84. return _body;
  85. }
  86. void PhysicsRigidBody::applyForce(const Vector3& force, const Vector3* relativePosition)
  87. {
  88. // If the force is significant enough, activate the rigid body
  89. // to make sure that it isn't sleeping and apply the force.
  90. if (force.lengthSquared() > MATH_EPSILON)
  91. {
  92. GP_ASSERT(_body);
  93. _body->activate();
  94. if (relativePosition)
  95. _body->applyForce(BV(force), BV(*relativePosition));
  96. else
  97. _body->applyCentralForce(BV(force));
  98. }
  99. }
  100. void PhysicsRigidBody::applyImpulse(const Vector3& impulse, const Vector3* relativePosition)
  101. {
  102. // If the impulse is significant enough, activate the rigid body
  103. // to make sure that it isn't sleeping and apply the impulse.
  104. if (impulse.lengthSquared() > MATH_EPSILON)
  105. {
  106. GP_ASSERT(_body);
  107. _body->activate();
  108. if (relativePosition)
  109. {
  110. _body->applyImpulse(BV(impulse), BV(*relativePosition));
  111. }
  112. else
  113. _body->applyCentralImpulse(BV(impulse));
  114. }
  115. }
  116. void PhysicsRigidBody::applyTorque(const Vector3& torque)
  117. {
  118. // If the torque is significant enough, activate the rigid body
  119. // to make sure that it isn't sleeping and apply the torque.
  120. if (torque.lengthSquared() > MATH_EPSILON)
  121. {
  122. GP_ASSERT(_body);
  123. _body->activate();
  124. _body->applyTorque(BV(torque));
  125. }
  126. }
  127. void PhysicsRigidBody::applyTorqueImpulse(const Vector3& torque)
  128. {
  129. // If the torque impulse is significant enough, activate the rigid body
  130. // to make sure that it isn't sleeping and apply the torque impulse.
  131. if (torque.lengthSquared() > MATH_EPSILON)
  132. {
  133. GP_ASSERT(_body);
  134. _body->activate();
  135. _body->applyTorqueImpulse(BV(torque));
  136. }
  137. }
  138. PhysicsRigidBody* PhysicsRigidBody::create(Node* node, Properties* properties, const char* nspace)
  139. {
  140. // Check if the properties is valid and has a valid namespace.
  141. if (!properties || !(strcmp(properties->getNamespace(), "collisionObject") == 0))
  142. {
  143. GP_ERROR("Failed to load rigid body from properties object: must be non-null object and have namespace equal to 'collisionObject'.");
  144. return NULL;
  145. }
  146. // Check that the type is specified and correct.
  147. const char* type = properties->getString("type");
  148. if (!type)
  149. {
  150. GP_ERROR("Failed to load physics rigid body from properties object; required attribute 'type' is missing.");
  151. return NULL;
  152. }
  153. if (strcmp(type, nspace) != 0)
  154. {
  155. GP_ERROR("Failed to load physics rigid body from properties object; attribute 'type' must be equal to '%s'.", nspace);
  156. return NULL;
  157. }
  158. // Load the physics collision shape definition.
  159. PhysicsCollisionShape::Definition shape = PhysicsCollisionShape::Definition::create(node, properties);
  160. if (shape.isEmpty())
  161. {
  162. GP_ERROR("Failed to create collision shape during rigid body creation.");
  163. return NULL;
  164. }
  165. // Set the rigid body parameters to their defaults.
  166. Parameters parameters;
  167. Vector3* gravity = NULL;
  168. // Load the defined rigid body parameters.
  169. properties->rewind();
  170. const char* name;
  171. while ((name = properties->getNextProperty()) != NULL)
  172. {
  173. if (strcmp(name, "mass") == 0)
  174. {
  175. parameters.mass = properties->getFloat();
  176. }
  177. else if (strcmp(name, "friction") == 0)
  178. {
  179. parameters.friction = properties->getFloat();
  180. }
  181. else if (strcmp(name, "restitution") == 0)
  182. {
  183. parameters.restitution = properties->getFloat();
  184. }
  185. else if (strcmp(name, "linearDamping") == 0)
  186. {
  187. parameters.linearDamping = properties->getFloat();
  188. }
  189. else if (strcmp(name, "angularDamping") == 0)
  190. {
  191. parameters.angularDamping = properties->getFloat();
  192. }
  193. else if (strcmp(name, "kinematic") == 0)
  194. {
  195. parameters.kinematic = properties->getBool();
  196. }
  197. else if (strcmp(name, "anisotropicFriction") == 0)
  198. {
  199. properties->getVector3(NULL, &parameters.anisotropicFriction);
  200. }
  201. else if (strcmp(name, "gravity") == 0)
  202. {
  203. gravity = new Vector3();
  204. properties->getVector3(NULL, gravity);
  205. }
  206. else if (strcmp(name, "angularFactor") == 0)
  207. {
  208. properties->getVector3(NULL, &parameters.angularFactor);
  209. }
  210. else if (strcmp(name, "linearFactor") == 0)
  211. {
  212. properties->getVector3(NULL, &parameters.linearFactor);
  213. }
  214. else
  215. {
  216. // Ignore this case (the attributes for the rigid body's collision shape would end up here).
  217. }
  218. }
  219. // Create the rigid body.
  220. PhysicsRigidBody* body = new PhysicsRigidBody(node, shape, parameters);
  221. if (gravity)
  222. {
  223. body->setGravity(*gravity);
  224. SAFE_DELETE(gravity);
  225. }
  226. return body;
  227. }
  228. void PhysicsRigidBody::setKinematic(bool kinematic)
  229. {
  230. GP_ASSERT(_body);
  231. if (kinematic)
  232. {
  233. _body->setCollisionFlags(_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
  234. _body->setActivationState(DISABLE_DEACTIVATION);
  235. }
  236. else
  237. {
  238. _body->setCollisionFlags(_body->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT);
  239. _body->setActivationState(ACTIVE_TAG);
  240. }
  241. }
  242. void PhysicsRigidBody::setEnabled(bool enable)
  243. {
  244. PhysicsCollisionObject::setEnabled(enable);
  245. if (enable)
  246. _body->setMotionState(_motionState);
  247. }
  248. float PhysicsRigidBody::getHeight(float x, float z) const
  249. {
  250. GP_ASSERT(_collisionShape);
  251. GP_ASSERT(_node);
  252. // If our node has a terrain, call getHeight() on it since we need to factor in local
  253. // scaling on the terrain into the height calculation.
  254. if (_node->getTerrain())
  255. return _node->getTerrain()->getHeight(x, z);
  256. // This function is only supported for heightfield rigid bodies.
  257. if (_collisionShape->getType() != PhysicsCollisionShape::SHAPE_HEIGHTFIELD)
  258. {
  259. GP_WARN("Attempting to get the height of a non-heightfield rigid body.");
  260. return 0.0f;
  261. }
  262. GP_ASSERT(_collisionShape->_shapeData.heightfieldData);
  263. // Ensure inverse matrix is updated so we can transform from world back into local heightfield coordinates for indexing
  264. if (_collisionShape->_shapeData.heightfieldData->inverseIsDirty)
  265. {
  266. _collisionShape->_shapeData.heightfieldData->inverseIsDirty = false;
  267. _node->getWorldMatrix().invert(&_collisionShape->_shapeData.heightfieldData->inverse);
  268. }
  269. // Calculate the correct x, z position relative to the heightfield data.
  270. float cols = _collisionShape->_shapeData.heightfieldData->heightfield->getColumnCount();
  271. float rows = _collisionShape->_shapeData.heightfieldData->heightfield->getRowCount();
  272. GP_ASSERT(cols > 0);
  273. GP_ASSERT(rows > 0);
  274. Vector3 v = _collisionShape->_shapeData.heightfieldData->inverse * Vector3(x, 0.0f, z);
  275. x = v.x + (cols - 1) * 0.5f;
  276. z = v.z + (rows - 1) * 0.5f;
  277. // Get the unscaled height value from the HeightField
  278. float height = _collisionShape->_shapeData.heightfieldData->heightfield->getHeight(x, z);
  279. // Apply scale back to height
  280. Vector3 worldScale;
  281. _node->getWorldMatrix().getScale(&worldScale);
  282. height *= worldScale.y;
  283. return height;
  284. }
  285. void PhysicsRigidBody::addConstraint(PhysicsConstraint* constraint)
  286. {
  287. GP_ASSERT(constraint);
  288. if (_constraints == NULL)
  289. _constraints = new std::vector<PhysicsConstraint*>();
  290. _constraints->push_back(constraint);
  291. }
  292. void PhysicsRigidBody::removeConstraint(PhysicsConstraint* constraint)
  293. {
  294. // Ensure that the rigid body has constraints and that we are
  295. // not currently in the rigid body's destructor (in this case,
  296. // the constraints will be destroyed from there).
  297. if (_constraints && !_inDestructor)
  298. {
  299. for (unsigned int i = 0; i < _constraints->size(); ++i)
  300. {
  301. if ((*_constraints)[i] == constraint)
  302. {
  303. _constraints->erase(_constraints->begin() + i);
  304. break;
  305. }
  306. }
  307. }
  308. }
  309. bool PhysicsRigidBody::supportsConstraints()
  310. {
  311. return (getShapeType() != PhysicsCollisionShape::SHAPE_HEIGHTFIELD && getShapeType() != PhysicsCollisionShape::SHAPE_MESH);
  312. }
  313. void PhysicsRigidBody::transformChanged(Transform* transform, long cookie)
  314. {
  315. if (getShapeType() == PhysicsCollisionShape::SHAPE_HEIGHTFIELD)
  316. {
  317. GP_ASSERT(_collisionShape && _collisionShape->_shapeData.heightfieldData);
  318. // Dirty the heightfield's inverse matrix (used to compute height values from world-space coordinates)
  319. _collisionShape->_shapeData.heightfieldData->inverseIsDirty = true;
  320. // Update local scaling for the heightfield.
  321. Vector3 scale;
  322. _node->getWorldMatrix().getScale(&scale);
  323. // If the node has a terrain attached, factor in the terrain local scaling as well for the collision shape
  324. if (_node->getTerrain())
  325. {
  326. Vector3& tScale = _node->getTerrain()->_localScale;
  327. scale.set(scale.x * tScale.x, scale.y * tScale.y, scale.z * tScale.z);
  328. }
  329. _collisionShape->_shape->setLocalScaling(BV(scale));
  330. // Update center of mass offset
  331. float minHeight = _collisionShape->_shapeData.heightfieldData->minHeight;
  332. float maxHeight = _collisionShape->_shapeData.heightfieldData->maxHeight;
  333. _motionState->setCenterOfMassOffset(Vector3(0, -(minHeight + (maxHeight-minHeight)*0.5f) * scale.y, 0));
  334. }
  335. }
  336. }