PhysicsWorld.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "BoxShape.h"
  25. #include "CapsuleShape.h"
  26. #include "ConeShape.h"
  27. #include "Context.h"
  28. #include "CylinderShape.h"
  29. #include "DebugRenderer.h"
  30. #include "Joint.h"
  31. #include "Log.h"
  32. #include "Mutex.h"
  33. #include "PhysicsEvents.h"
  34. #include "PhysicsUtils.h"
  35. #include "PhysicsWorld.h"
  36. #include "Profiler.h"
  37. #include "Ray.h"
  38. #include "RigidBody.h"
  39. #include "Scene.h"
  40. #include "SceneEvents.h"
  41. #include "Sort.h"
  42. #include "SphereShape.h"
  43. #include "TriangleMeshShape.h"
  44. #include <BulletCollision/BroadphaseCollision/btDbvtBroadphase.h>
  45. #include <BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h>
  46. #include <BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h>
  47. #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  48. #include "DebugNew.h"
  49. static const int DEFAULT_FPS = 60;
  50. static const Vector3 DEFAULT_GRAVITY = Vector3(0.0f, -9.81f, 0.0f);
  51. static bool CompareRaycastResults(const PhysicsRaycastResult& lhs, const PhysicsRaycastResult& rhs)
  52. {
  53. return lhs.distance_ < rhs.distance_;
  54. }
  55. void InternalPreTickCallback(btDynamicsWorld *world, btScalar timeStep)
  56. {
  57. static_cast<PhysicsWorld*>(world->getWorldUserInfo())->PreStep(timeStep);
  58. }
  59. void InternalTickCallback(btDynamicsWorld *world, btScalar timeStep)
  60. {
  61. static_cast<PhysicsWorld*>(world->getWorldUserInfo())->PostStep(timeStep);
  62. }
  63. OBJECTTYPESTATIC(PhysicsWorld);
  64. PhysicsWorld::PhysicsWorld(Context* context) :
  65. Component(context),
  66. collisionConfiguration_(0),
  67. collisionDispatcher_(0),
  68. broadphase_(0),
  69. solver_(0),
  70. world_(0),
  71. fps_(DEFAULT_FPS),
  72. timeAcc_(0.0f),
  73. maxNetworkAngularVelocity_(DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY),
  74. interpolation_(true),
  75. debugRenderer_(0),
  76. debugMode_(btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawNormals | btIDebugDraw::DBG_DrawConstraints)
  77. {
  78. collisionConfiguration_ = new btDefaultCollisionConfiguration();
  79. collisionDispatcher_ = new btCollisionDispatcher(collisionConfiguration_);
  80. broadphase_ = new btDbvtBroadphase();
  81. solver_ = new btSequentialImpulseConstraintSolver();
  82. world_ = new btDiscreteDynamicsWorld(collisionDispatcher_, broadphase_, solver_, collisionConfiguration_);
  83. world_->setGravity(ToBtVector3(DEFAULT_GRAVITY));
  84. world_->setDebugDrawer(this);
  85. world_->setInternalTickCallback(InternalPreTickCallback, static_cast<void*>(this), true);
  86. world_->setInternalTickCallback(InternalTickCallback, static_cast<void*>(this), false);
  87. }
  88. PhysicsWorld::~PhysicsWorld()
  89. {
  90. if (scene_)
  91. {
  92. // Force all remaining joints, rigid bodies and collision shapes to release themselves
  93. for (PODVector<Joint*>::Iterator i = joints_.Begin(); i != joints_.End(); ++i)
  94. (*i)->Clear();
  95. for (PODVector<RigidBody*>::Iterator i = rigidBodies_.Begin(); i != rigidBodies_.End(); ++i)
  96. (*i)->ReleaseBody();
  97. }
  98. // Remove any cached geometries that still remain
  99. triangleMeshCache_.Clear();
  100. heightfieldCache_.Clear();
  101. delete world_;
  102. world_ = 0;
  103. delete solver_;
  104. solver_ = 0;
  105. delete broadphase_;
  106. broadphase_ = 0;
  107. delete collisionDispatcher_;
  108. collisionDispatcher_ = 0;
  109. delete collisionConfiguration_;
  110. collisionConfiguration_ = 0;
  111. }
  112. void PhysicsWorld::RegisterObject(Context* context)
  113. {
  114. context->RegisterFactory<PhysicsWorld>();
  115. ACCESSOR_ATTRIBUTE(PhysicsWorld, VAR_VECTOR3, "Gravity", GetGravity, SetGravity, Vector3, DEFAULT_GRAVITY, AM_DEFAULT);
  116. ATTRIBUTE(PhysicsWorld, VAR_INT, "Physics FPS", fps_, DEFAULT_FPS, AM_DEFAULT);
  117. ATTRIBUTE(PhysicsWorld, VAR_FLOAT, "Net Max Angular Vel.", maxNetworkAngularVelocity_, DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY, AM_DEFAULT);
  118. ATTRIBUTE(PhysicsWorld, VAR_BOOL, "Interpolation", interpolation_, true, AM_FILE);
  119. }
  120. void PhysicsWorld::drawLine(const btVector3& from, const btVector3& to, const btVector3& color)
  121. {
  122. if (debugRenderer_)
  123. debugRenderer_->AddLine(ToVector3(from), ToVector3(to), Color(color.x(), color.y(), color.z()), debugDepthTest_);
  124. }
  125. void PhysicsWorld::reportErrorWarning(const char* warningString)
  126. {
  127. LOGWARNING("Physics: " + String(warningString));
  128. }
  129. void PhysicsWorld::Update(float timeStep)
  130. {
  131. PROFILE(UpdatePhysics);
  132. float internalTimeStep = 1.0f / fps_;
  133. if (interpolation_)
  134. {
  135. float minFps = 1.0f;
  136. int maxSubSteps = (int)((float)fps_ / minFps);
  137. world_->stepSimulation(timeStep, maxSubSteps, internalTimeStep);
  138. }
  139. else
  140. {
  141. timeAcc_ += timeStep;
  142. while (timeAcc_ >= internalTimeStep)
  143. {
  144. world_->stepSimulation(internalTimeStep, 0, internalTimeStep);
  145. timeAcc_ -= internalTimeStep;
  146. }
  147. }
  148. }
  149. void PhysicsWorld::SetFps(int fps)
  150. {
  151. fps_ = Clamp(fps, 1, 1000);
  152. }
  153. void PhysicsWorld::SetGravity(Vector3 gravity)
  154. {
  155. world_->setGravity(ToBtVector3(gravity));
  156. }
  157. void PhysicsWorld::SetInterpolation(bool enable)
  158. {
  159. interpolation_ = enable;
  160. }
  161. void PhysicsWorld::SetMaxNetworkAngularVelocity(float velocity)
  162. {
  163. maxNetworkAngularVelocity_ = Clamp(velocity, 1.0f, 32767.0f);
  164. }
  165. void PhysicsWorld::Raycast(PODVector<PhysicsRaycastResult>& result, const Ray& ray, float maxDistance, unsigned collisionMask)
  166. {
  167. /// \todo Implement
  168. }
  169. void PhysicsWorld::RaycastSingle(PhysicsRaycastResult& result, const Ray& ray, float maxDistance, unsigned collisionMask)
  170. {
  171. /// \todo Implement
  172. }
  173. Vector3 PhysicsWorld::GetGravity() const
  174. {
  175. return ToVector3(world_->getGravity());
  176. }
  177. void PhysicsWorld::AddRigidBody(RigidBody* body)
  178. {
  179. rigidBodies_.Push(body);
  180. }
  181. void PhysicsWorld::RemoveRigidBody(RigidBody* body)
  182. {
  183. PODVector<RigidBody*>::Iterator i = rigidBodies_.Find(body);
  184. if (i != rigidBodies_.End())
  185. rigidBodies_.Erase(i);
  186. }
  187. void PhysicsWorld::AddCollisionShape(CollisionShape* shape)
  188. {
  189. collisionShapes_.Push(shape);
  190. }
  191. void PhysicsWorld::RemoveCollisionShape(CollisionShape* shape)
  192. {
  193. PODVector<CollisionShape*>::Iterator i = collisionShapes_.Find(shape);
  194. if (i != collisionShapes_.End())
  195. collisionShapes_.Erase(i);
  196. }
  197. void PhysicsWorld::AddJoint(Joint* joint)
  198. {
  199. joints_.Push(joint);
  200. }
  201. void PhysicsWorld::RemoveJoint(Joint* joint)
  202. {
  203. PODVector<Joint*>::Iterator i = joints_.Find(joint);
  204. if (i != joints_.End())
  205. joints_.Erase(i);
  206. }
  207. void PhysicsWorld::DrawDebugGeometry(bool depthTest)
  208. {
  209. debugDepthTest_ = depthTest;
  210. debugRenderer_ = GetComponent<DebugRenderer>();
  211. world_->debugDrawWorld();
  212. debugRenderer_ = 0;
  213. }
  214. void PhysicsWorld::CleanupGeometryCache()
  215. {
  216. // Remove cached shapes whose only reference is the cache itself
  217. for (Map<String, SharedPtr<TriangleMeshData> >::Iterator i = triangleMeshCache_.Begin();
  218. i != triangleMeshCache_.End();)
  219. {
  220. Map<String, SharedPtr<TriangleMeshData> >::Iterator current = i++;
  221. if (current->second_.Refs() == 1)
  222. triangleMeshCache_.Erase(current);
  223. }
  224. for (Map<String, SharedPtr<ConvexHullData> >::Iterator i = convexHullCache_.Begin();
  225. i != convexHullCache_.End();)
  226. {
  227. Map<String, SharedPtr<ConvexHullData> >::Iterator current = i++;
  228. if (current->second_.Refs() == 1)
  229. convexHullCache_.Erase(current);
  230. }
  231. for (Map<String, SharedPtr<HeightfieldData> >::Iterator i = heightfieldCache_.Begin();
  232. i != heightfieldCache_.End();)
  233. {
  234. Map<String, SharedPtr<HeightfieldData> >::Iterator current = i++;
  235. if (current->second_.Refs() == 1)
  236. heightfieldCache_.Erase(current);
  237. }
  238. }
  239. void PhysicsWorld::OnNodeSet(Node* node)
  240. {
  241. // Subscribe to the scene subsystem update, which will trigger the physics simulation step
  242. if (node)
  243. {
  244. scene_ = node->GetScene();
  245. SubscribeToEvent(node, E_SCENESUBSYSTEMUPDATE, HANDLER(PhysicsWorld, HandleSceneSubsystemUpdate));
  246. }
  247. }
  248. void PhysicsWorld::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData)
  249. {
  250. using namespace SceneSubsystemUpdate;
  251. Update(eventData[P_TIMESTEP].GetFloat());
  252. }
  253. void PhysicsWorld::PreStep(float timeStep)
  254. {
  255. // Send pre-step event
  256. using namespace PhysicsPreStep;
  257. VariantMap eventData;
  258. eventData[P_WORLD] = (void*)this;
  259. eventData[P_TIMESTEP] = timeStep;
  260. SendEvent(E_PHYSICSPRESTEP, eventData);
  261. }
  262. void PhysicsWorld::PostStep(float timeStep)
  263. {
  264. SendCollisionEvents();
  265. // Send post-step event
  266. using namespace PhysicsPreStep;
  267. VariantMap eventData;
  268. eventData[P_WORLD] = (void*)this;
  269. eventData[P_TIMESTEP] = timeStep;
  270. SendEvent(E_PHYSICSPOSTSTEP, eventData);
  271. }
  272. void PhysicsWorld::SendCollisionEvents()
  273. {
  274. /// \todo Implement
  275. }
  276. void RegisterPhysicsLibrary(Context* context)
  277. {
  278. Joint::RegisterObject(context);
  279. RigidBody::RegisterObject(context);
  280. BoxShape::RegisterObject(context);
  281. CapsuleShape::RegisterObject(context);
  282. ConeShape::RegisterObject(context);
  283. CylinderShape::RegisterObject(context);
  284. SphereShape::RegisterObject(context);
  285. TriangleMeshShape::RegisterObject(context);
  286. PhysicsWorld::RegisterObject(context);
  287. }