b2World.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. /*
  2. * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
  3. * Copyright (c) 2013 Google, Inc.
  4. *
  5. * This software is provided 'as-is', without any express or implied
  6. * warranty. In no event will the authors be held liable for any damages
  7. * arising from the use of this software.
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. * 1. The origin of this software must not be misrepresented; you must not
  12. * claim that you wrote the original software. If you use this software
  13. * in a product, an acknowledgment in the product documentation would be
  14. * appreciated but is not required.
  15. * 2. Altered source versions must be plainly marked as such, and must not be
  16. * misrepresented as being the original software.
  17. * 3. This notice may not be removed or altered from any source distribution.
  18. */
  19. #ifndef B2_WORLD_H
  20. #define B2_WORLD_H
  21. #include <Box2D/Common/b2Math.h>
  22. #include <Box2D/Common/b2BlockAllocator.h>
  23. #include <Box2D/Common/b2StackAllocator.h>
  24. #include <Box2D/Dynamics/b2ContactManager.h>
  25. #include <Box2D/Dynamics/b2WorldCallbacks.h>
  26. #include <Box2D/Dynamics/b2TimeStep.h>
  27. #include <Box2D/Particle/b2ParticleSystem.h>
  28. struct b2AABB;
  29. struct b2BodyDef;
  30. struct b2Color;
  31. struct b2JointDef;
  32. class b2Body;
  33. class b2Draw;
  34. class b2Fixture;
  35. class b2Joint;
  36. class b2ParticleGroup;
  37. /// The world class manages all physics entities, dynamic simulation,
  38. /// and asynchronous queries. The world also contains efficient memory
  39. /// management facilities.
  40. class b2World
  41. {
  42. public:
  43. /// Construct a world object.
  44. /// @param gravity the world gravity vector.
  45. b2World(const b2Vec2& gravity);
  46. /// Destruct the world. All physics entities are destroyed and all heap memory is released.
  47. ~b2World();
  48. /// Register a destruction listener. The listener is owned by you and must
  49. /// remain in scope.
  50. void SetDestructionListener(b2DestructionListener* listener);
  51. /// Register a contact filter to provide specific control over collision.
  52. /// Otherwise the default filter is used (b2_defaultFilter). The listener is
  53. /// owned by you and must remain in scope.
  54. void SetContactFilter(b2ContactFilter* filter);
  55. /// Register a contact event listener. The listener is owned by you and must
  56. /// remain in scope.
  57. void SetContactListener(b2ContactListener* listener);
  58. /// Register a routine for debug drawing. The debug draw functions are called
  59. /// inside with b2World::DrawDebugData method. The debug draw object is owned
  60. /// by you and must remain in scope.
  61. void SetDebugDraw(b2Draw* debugDraw);
  62. /// Create a rigid body given a definition. No reference to the definition
  63. /// is retained.
  64. /// @warning This function is locked during callbacks.
  65. b2Body* CreateBody(const b2BodyDef* def);
  66. /// Destroy a rigid body.
  67. /// This function is locked during callbacks.
  68. /// @warning This automatically deletes all associated shapes and joints.
  69. /// @warning This function is locked during callbacks.
  70. void DestroyBody(b2Body* body);
  71. /// Create a joint to constrain bodies together. No reference to the definition
  72. /// is retained. This may cause the connected bodies to cease colliding.
  73. /// @warning This function is locked during callbacks.
  74. b2Joint* CreateJoint(const b2JointDef* def);
  75. /// Destroy a joint. This may cause the connected bodies to begin colliding.
  76. /// @warning This function is locked during callbacks.
  77. void DestroyJoint(b2Joint* joint);
  78. /// Create a particle system given a definition. No reference to the
  79. /// definition is retained.
  80. /// @warning This function is locked during callbacks.
  81. b2ParticleSystem* CreateParticleSystem(const b2ParticleSystemDef* def);
  82. /// Destroy a particle system.
  83. /// @warning This function is locked during callbacks.
  84. void DestroyParticleSystem(b2ParticleSystem* p);
  85. /// Take a time step. This performs collision detection, integration,
  86. /// and constraint solution.
  87. /// For the numerical stability of particles, minimize the following
  88. /// dimensionless gravity acceleration:
  89. /// gravity / particleRadius * (timeStep / particleIterations)^2
  90. /// b2CalculateParticleIterations() or
  91. /// CalculateReasonableParticleIterations() help to determine the optimal
  92. /// particleIterations.
  93. /// @param timeStep the amount of time to simulate, this should not vary.
  94. /// @param velocityIterations for the velocity constraint solver.
  95. /// @param positionIterations for the position constraint solver.
  96. /// @param particleIterations for the particle simulation.
  97. void Step( float32 timeStep,
  98. int32 velocityIterations,
  99. int32 positionIterations,
  100. int32 particleIterations);
  101. /// Take a time step. This performs collision detection, integration,
  102. /// and constraint solution.
  103. /// @param timeStep the amount of time to simulate, this should not vary.
  104. /// @param velocityIterations for the velocity constraint solver.
  105. /// @param positionIterations for the position constraint solver.
  106. void Step( float32 timeStep,
  107. int32 velocityIterations,
  108. int32 positionIterations)
  109. {
  110. Step(timeStep, velocityIterations, positionIterations, 1);
  111. }
  112. /// Recommend a value to be used in `Step` for `particleIterations`.
  113. /// This calculation is necessarily a simplification and should only be
  114. /// used as a starting point. Please see "Particle Iterations" in the
  115. /// Programmer's Guide for details.
  116. /// @param timeStep is the value to be passed into `Step`.
  117. int CalculateReasonableParticleIterations(float32 timeStep) const;
  118. /// Manually clear the force buffer on all bodies. By default, forces are cleared automatically
  119. /// after each call to Step. The default behavior is modified by calling SetAutoClearForces.
  120. /// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain
  121. /// a fixed sized time step under a variable frame-rate.
  122. /// When you perform sub-stepping you will disable auto clearing of forces and instead call
  123. /// ClearForces after all sub-steps are complete in one pass of your game loop.
  124. /// @see SetAutoClearForces
  125. void ClearForces();
  126. /// Call this to draw shapes and other debug draw data. This is intentionally non-const.
  127. void DrawDebugData();
  128. /// Query the world for all fixtures that potentially overlap the
  129. /// provided AABB.
  130. /// @param callback a user implemented callback class.
  131. /// @param aabb the query box.
  132. void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const;
  133. /// Query the world for all fixtures that potentially overlap the
  134. /// provided shape's AABB. Calls QueryAABB internally.
  135. /// @param callback a user implemented callback class.
  136. /// @param shape the query shape
  137. /// @param xf the transform of the AABB
  138. void QueryShapeAABB(b2QueryCallback* callback, const b2Shape& shape,
  139. const b2Transform& xf) const;
  140. /// Ray-cast the world for all fixtures in the path of the ray. Your callback
  141. /// controls whether you get the closest point, any point, or n-points.
  142. /// The ray-cast ignores shapes that contain the starting point.
  143. /// @param callback a user implemented callback class.
  144. /// @param point1 the ray starting point
  145. /// @param point2 the ray ending point
  146. void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const;
  147. /// Get the world body list. With the returned body, use b2Body::GetNext to get
  148. /// the next body in the world list. A NULL body indicates the end of the list.
  149. /// @return the head of the world body list.
  150. b2Body* GetBodyList();
  151. const b2Body* GetBodyList() const;
  152. /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get
  153. /// the next joint in the world list. A NULL joint indicates the end of the list.
  154. /// @return the head of the world joint list.
  155. b2Joint* GetJointList();
  156. const b2Joint* GetJointList() const;
  157. /// Get the world particle-system list. With the returned body, use
  158. /// b2ParticleSystem::GetNext to get the next particle-system in the world
  159. /// list. A NULL particle-system indicates the end of the list.
  160. /// @return the head of the world particle-system list.
  161. b2ParticleSystem* GetParticleSystemList();
  162. const b2ParticleSystem* GetParticleSystemList() const;
  163. /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get
  164. /// the next contact in the world list. A NULL contact indicates the end of the list.
  165. /// @return the head of the world contact list.
  166. /// @warning contacts are created and destroyed in the middle of a time step.
  167. /// Use b2ContactListener to avoid missing contacts.
  168. b2Contact* GetContactList();
  169. const b2Contact* GetContactList() const;
  170. /// Enable/disable sleep.
  171. void SetAllowSleeping(bool flag);
  172. bool GetAllowSleeping() const { return m_allowSleep; }
  173. /// Enable/disable warm starting. For testing.
  174. void SetWarmStarting(bool flag) { m_warmStarting = flag; }
  175. bool GetWarmStarting() const { return m_warmStarting; }
  176. /// Enable/disable continuous physics. For testing.
  177. void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; }
  178. bool GetContinuousPhysics() const { return m_continuousPhysics; }
  179. /// Enable/disable single stepped continuous physics. For testing.
  180. void SetSubStepping(bool flag) { m_subStepping = flag; }
  181. bool GetSubStepping() const { return m_subStepping; }
  182. /// Get the number of broad-phase proxies.
  183. int32 GetProxyCount() const;
  184. /// Get the number of bodies.
  185. int32 GetBodyCount() const;
  186. /// Get the number of joints.
  187. int32 GetJointCount() const;
  188. /// Get the number of contacts (each may have 0 or more contact points).
  189. int32 GetContactCount() const;
  190. /// Get the height of the dynamic tree.
  191. int32 GetTreeHeight() const;
  192. /// Get the balance of the dynamic tree.
  193. int32 GetTreeBalance() const;
  194. /// Get the quality metric of the dynamic tree. The smaller the better.
  195. /// The minimum is 1.
  196. float32 GetTreeQuality() const;
  197. /// Change the global gravity vector.
  198. void SetGravity(const b2Vec2& gravity);
  199. /// Get the global gravity vector.
  200. b2Vec2 GetGravity() const;
  201. /// Is the world locked (in the middle of a time step).
  202. bool IsLocked() const;
  203. /// Set flag to control automatic clearing of forces after each time step.
  204. void SetAutoClearForces(bool flag);
  205. /// Get the flag that controls automatic clearing of forces after each time step.
  206. bool GetAutoClearForces() const;
  207. /// Shift the world origin. Useful for large worlds.
  208. /// The body shift formula is: position -= newOrigin
  209. /// @param newOrigin the new origin with respect to the old origin
  210. void ShiftOrigin(const b2Vec2& newOrigin);
  211. /// Get the contact manager for testing.
  212. const b2ContactManager& GetContactManager() const;
  213. /// Get the current profile.
  214. const b2Profile& GetProfile() const;
  215. /// Dump the world into the log file.
  216. /// @warning this should be called outside of a time step.
  217. void Dump();
  218. /// Get API version.
  219. const b2Version* GetVersion() const {
  220. return m_liquidFunVersion;
  221. }
  222. /// Get API version string.
  223. const char* GetVersionString() const {
  224. return m_liquidFunVersionString;
  225. }
  226. #if LIQUIDFUN_EXTERNAL_LANGUAGE_API
  227. public:
  228. /// Constructor which takes direct floats.
  229. b2World(float32 gravityX, float32 gravityY);
  230. /// Set gravity with direct floats.
  231. void SetGravity(float32 gravityX, float32 gravityY);
  232. #endif // LIQUIDFUN_EXTERNAL_LANGUAGE_API
  233. private:
  234. // m_flags
  235. enum
  236. {
  237. e_newFixture = 0x0001,
  238. e_locked = 0x0002,
  239. e_clearForces = 0x0004
  240. };
  241. friend class b2Body;
  242. friend class b2Fixture;
  243. friend class b2ContactManager;
  244. friend class b2Controller;
  245. friend class b2ParticleSystem;
  246. void Init(const b2Vec2& gravity);
  247. void Solve(const b2TimeStep& step);
  248. void SolveTOI(const b2TimeStep& step);
  249. void DrawJoint(b2Joint* joint);
  250. void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color);
  251. void DrawParticleSystem(const b2ParticleSystem& system);
  252. b2BlockAllocator m_blockAllocator;
  253. b2StackAllocator m_stackAllocator;
  254. int32 m_flags;
  255. b2ContactManager m_contactManager;
  256. b2Body* m_bodyList;
  257. b2Joint* m_jointList;
  258. b2ParticleSystem* m_particleSystemList;
  259. int32 m_bodyCount;
  260. int32 m_jointCount;
  261. b2Vec2 m_gravity;
  262. bool m_allowSleep;
  263. b2DestructionListener* m_destructionListener;
  264. b2Draw* m_debugDraw;
  265. // This is used to compute the time step ratio to
  266. // support a variable time step.
  267. float32 m_inv_dt0;
  268. // These are for debugging the solver.
  269. bool m_warmStarting;
  270. bool m_continuousPhysics;
  271. bool m_subStepping;
  272. bool m_stepComplete;
  273. b2Profile m_profile;
  274. /// Used to reference b2_LiquidFunVersion so that it's not stripped from
  275. /// the static library.
  276. const b2Version *m_liquidFunVersion;
  277. const char *m_liquidFunVersionString;
  278. };
  279. inline b2Body* b2World::GetBodyList()
  280. {
  281. return m_bodyList;
  282. }
  283. inline const b2Body* b2World::GetBodyList() const
  284. {
  285. return m_bodyList;
  286. }
  287. inline b2Joint* b2World::GetJointList()
  288. {
  289. return m_jointList;
  290. }
  291. inline const b2Joint* b2World::GetJointList() const
  292. {
  293. return m_jointList;
  294. }
  295. inline b2ParticleSystem* b2World::GetParticleSystemList()
  296. {
  297. return m_particleSystemList;
  298. }
  299. inline const b2ParticleSystem* b2World::GetParticleSystemList() const
  300. {
  301. return m_particleSystemList;
  302. }
  303. inline b2Contact* b2World::GetContactList()
  304. {
  305. return m_contactManager.m_contactList;
  306. }
  307. inline const b2Contact* b2World::GetContactList() const
  308. {
  309. return m_contactManager.m_contactList;
  310. }
  311. inline int32 b2World::GetBodyCount() const
  312. {
  313. return m_bodyCount;
  314. }
  315. inline int32 b2World::GetJointCount() const
  316. {
  317. return m_jointCount;
  318. }
  319. inline int32 b2World::GetContactCount() const
  320. {
  321. return m_contactManager.m_contactCount;
  322. }
  323. inline void b2World::SetGravity(const b2Vec2& gravity)
  324. {
  325. m_gravity = gravity;
  326. }
  327. inline b2Vec2 b2World::GetGravity() const
  328. {
  329. return m_gravity;
  330. }
  331. inline bool b2World::IsLocked() const
  332. {
  333. return (m_flags & e_locked) == e_locked;
  334. }
  335. inline void b2World::SetAutoClearForces(bool flag)
  336. {
  337. if (flag)
  338. {
  339. m_flags |= e_clearForces;
  340. }
  341. else
  342. {
  343. m_flags &= ~e_clearForces;
  344. }
  345. }
  346. /// Get the flag that controls automatic clearing of forces after each time step.
  347. inline bool b2World::GetAutoClearForces() const
  348. {
  349. return (m_flags & e_clearForces) == e_clearForces;
  350. }
  351. inline const b2ContactManager& b2World::GetContactManager() const
  352. {
  353. return m_contactManager;
  354. }
  355. inline const b2Profile& b2World::GetProfile() const
  356. {
  357. return m_profile;
  358. }
  359. #if LIQUIDFUN_EXTERNAL_LANGUAGE_API
  360. inline b2World::b2World(float32 gravityX, float32 gravityY)
  361. {
  362. Init(b2Vec2(gravityX, gravityY));
  363. }
  364. inline void b2World::SetGravity(float32 gravityX, float32 gravityY)
  365. {
  366. SetGravity(b2Vec2(gravityX, gravityY));
  367. }
  368. #endif // LIQUIDFUN_EXTERNAL_LANGUAGE_API
  369. #endif