PhysicsWorld.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /*
  2. Copyright (c) 2013 Daniele Bartolini, Michele Rossi
  3. Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation
  6. files (the "Software"), to deal in the Software without
  7. restriction, including without limitation the rights to use,
  8. copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the
  10. Software is furnished to do so, subject to the following
  11. conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  16. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  21. OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #include "PhysicsWorld.h"
  24. #include "Vector3.h"
  25. #include "Actor.h"
  26. #include "Device.h"
  27. #include "Quaternion.h"
  28. #include "SceneGraph.h"
  29. #include "Controller.h"
  30. #include "Trigger.h"
  31. #include "Joint.h"
  32. #include "PhysicsCallback.h"
  33. #include "ProxyAllocator.h"
  34. #include "Hash.h"
  35. #include "StringUtils.h"
  36. #include "Actor.h"
  37. #include "ResourceManager.h"
  38. #include "Raycast.h"
  39. #include "PxPhysicsAPI.h"
  40. using physx::PxSceneDesc;
  41. using physx::PxVec3;
  42. using physx::PxTransform;
  43. using physx::PxQuat;
  44. using physx::PxHalfPi;
  45. using physx::PxPlaneGeometry;
  46. using physx::PxMaterial;
  47. using physx::PxShape;
  48. using physx::PxRigidStatic;
  49. using physx::PxActiveTransform;
  50. using physx::PxU32;
  51. using physx::PxSceneFlag;
  52. using physx::PxFilterFlags;
  53. using physx::PxFilterData;
  54. using physx::PxPairFlags;
  55. using physx::PxFilterObjectAttributes;
  56. using physx::PxFilterObjectIsTrigger;
  57. using physx::PxPairFlag;
  58. using physx::PxFilterFlag;
  59. using physx::PxSceneLimits;
  60. using physx::PxVisualizationParameter;
  61. namespace crown
  62. {
  63. namespace physics_system
  64. {
  65. using physx::PxFoundation;
  66. using physx::PxPhysics;
  67. using physx::PxCooking;
  68. using physx::PxCookingParams;
  69. using physx::PxTolerancesScale;
  70. using physx::PxAllocatorCallback;
  71. using physx::PxErrorCallback;
  72. using physx::PxErrorCode;
  73. //-----------------------------------------------------------------------------
  74. class PhysXAllocator : public PxAllocatorCallback
  75. {
  76. public:
  77. PhysXAllocator()
  78. : m_backing("physics", default_allocator())
  79. {
  80. }
  81. void* allocate(size_t size, const char*, const char*, int)
  82. {
  83. return m_backing.allocate(size, 16);
  84. }
  85. void deallocate(void* p)
  86. {
  87. m_backing.deallocate(p);
  88. }
  89. private:
  90. ProxyAllocator m_backing;
  91. };
  92. //-----------------------------------------------------------------------------
  93. class PhysXError : public PxErrorCallback
  94. {
  95. public:
  96. void reportError(PxErrorCode::Enum code, const char* message, const char* /*file*/, int /*line*/)
  97. {
  98. switch (code)
  99. {
  100. case PxErrorCode::eDEBUG_INFO:
  101. {
  102. Log::i("PhysX: %s", message);
  103. break;
  104. }
  105. case PxErrorCode::eDEBUG_WARNING:
  106. case PxErrorCode::ePERF_WARNING:
  107. {
  108. Log::w("PhysX: %s", message);
  109. break;
  110. }
  111. case PxErrorCode::eINVALID_PARAMETER:
  112. case PxErrorCode::eINVALID_OPERATION:
  113. case PxErrorCode::eOUT_OF_MEMORY:
  114. case PxErrorCode::eINTERNAL_ERROR:
  115. case PxErrorCode::eABORT:
  116. {
  117. CE_ASSERT(false, "PhysX: %s", message);
  118. break;
  119. }
  120. default:
  121. {
  122. CE_FATAL("Oops, unknown physx error");
  123. break;
  124. }
  125. }
  126. }
  127. };
  128. //-----------------------------------------------------------------------------
  129. PxFilterFlags FilterShader(PxFilterObjectAttributes attributes0, PxFilterData filterData0,
  130. PxFilterObjectAttributes attributes1, PxFilterData filterData1,
  131. PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize)
  132. {
  133. // let triggers through
  134. if(PxFilterObjectIsTrigger(attributes0) || PxFilterObjectIsTrigger(attributes1))
  135. {
  136. pairFlags = PxPairFlag::eTRIGGER_DEFAULT;
  137. return PxFilterFlag::eDEFAULT;
  138. }
  139. // generate contacts for all that were not filtered above
  140. pairFlags = PxPairFlag::eCONTACT_DEFAULT;
  141. // trigger the contact callback for pairs (A,B) where
  142. // the filtermask of A contains the ID of B and vice versa.
  143. if((filterData0.word0 & filterData1.word1) && (filterData1.word0 & filterData0.word1))
  144. {
  145. pairFlags |= PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_CONTACT_POINTS;
  146. return PxFilterFlag::eDEFAULT;
  147. }
  148. return PxFilterFlag::eDEFAULT;
  149. }
  150. // Global PhysX objects
  151. static PhysXAllocator* s_px_allocator;
  152. static PhysXError* s_px_error;
  153. static PxFoundation* s_foundation;
  154. static PxPhysics* s_physics;
  155. static PxCooking* s_cooking;
  156. void init()
  157. {
  158. s_px_allocator = CE_NEW(default_allocator(), PhysXAllocator)();
  159. s_px_error = CE_NEW(default_allocator(), PhysXError)();
  160. s_foundation = PxCreateFoundation(PX_PHYSICS_VERSION, *s_px_allocator, *s_px_error);
  161. CE_ASSERT(s_foundation, "Unable to create PhysX Foundation");
  162. s_physics = PxCreatePhysics(PX_PHYSICS_VERSION, *s_foundation, physx::PxTolerancesScale());
  163. CE_ASSERT(s_physics, "Unable to create PhysX Physics");
  164. bool extension = PxInitExtensions(*s_physics);
  165. CE_ASSERT(extension, "Unable to initialize PhysX Extensions");
  166. s_cooking = PxCreateCooking(PX_PHYSICS_VERSION, *s_foundation, PxCookingParams(PxTolerancesScale()));
  167. CE_ASSERT(s_cooking, "Unable to create PhysX Cooking");
  168. }
  169. void shutdown()
  170. {
  171. PxCloseExtensions();
  172. s_cooking->release();
  173. s_physics->release();
  174. s_foundation->release();
  175. CE_DELETE(default_allocator(), s_px_error);
  176. CE_DELETE(default_allocator(), s_px_allocator);
  177. }
  178. } // namespace physics_system
  179. //-----------------------------------------------------------------------------
  180. PhysicsWorld::PhysicsWorld()
  181. : m_scene(NULL)
  182. , m_actors_pool(default_allocator(), CE_MAX_ACTORS, sizeof(Actor), CE_ALIGNOF(Actor))
  183. , m_controllers_pool(default_allocator(), CE_MAX_CONTROLLERS, sizeof(Controller), CE_ALIGNOF(Controller))
  184. , m_triggers_pool(default_allocator(), CE_MAX_TRIGGERS, sizeof(Trigger), CE_ALIGNOF(Trigger))
  185. , m_joints_pool(default_allocator(), CE_MAX_JOINTS, sizeof(Joint), CE_ALIGNOF(Joint))
  186. , m_events(default_allocator())
  187. , m_callback(m_events)
  188. {
  189. // Create the scene
  190. PxSceneLimits scene_limits;
  191. scene_limits.maxNbActors = CE_MAX_ACTORS;
  192. CE_ASSERT(scene_limits.isValid(), "Scene limits is not valid");
  193. PxSceneDesc scene_desc(physics_system::s_physics->getTolerancesScale());
  194. scene_desc.gravity = PxVec3(0.0f, -9.81f, 0.0f);
  195. scene_desc.limits = scene_limits;
  196. scene_desc.filterShader = physics_system::FilterShader;
  197. scene_desc.simulationEventCallback = &m_callback;
  198. scene_desc.flags = PxSceneFlag::eENABLE_ACTIVETRANSFORMS
  199. | PxSceneFlag::eENABLE_KINEMATIC_STATIC_PAIRS
  200. | PxSceneFlag::eENABLE_KINEMATIC_PAIRS;
  201. if(!scene_desc.cpuDispatcher)
  202. {
  203. m_cpu_dispatcher = physx::PxDefaultCpuDispatcherCreate(1);
  204. CE_ASSERT(m_cpu_dispatcher != NULL, "Failed to create PhysX cpu dispatcher");
  205. scene_desc.cpuDispatcher = m_cpu_dispatcher;
  206. }
  207. CE_ASSERT(scene_desc.isValid(), "Scene is not valid");
  208. m_scene = physics_system::s_physics->createScene(scene_desc);
  209. // Create controller manager
  210. m_controller_manager = PxCreateControllerManager(*m_scene);
  211. CE_ASSERT(m_controller_manager != NULL, "Failed to create PhysX controller manager");
  212. }
  213. //-----------------------------------------------------------------------------
  214. PhysicsWorld::~PhysicsWorld()
  215. {
  216. m_cpu_dispatcher->release();
  217. m_controller_manager->release();
  218. m_scene->release();
  219. }
  220. //-----------------------------------------------------------------------------
  221. ActorId PhysicsWorld::create_actor(const PhysicsResource* res, const uint32_t index, SceneGraph& sg, int32_t node)
  222. {
  223. PhysicsConfigResource* config = (PhysicsConfigResource*) device()->resource_manager()->lookup("physics_config", "global");
  224. Actor* actor = CE_NEW(m_actors_pool, Actor)(res, config, index, physics_system::s_physics, physics_system::s_cooking, m_scene, sg, node, Vector3::ZERO, Quaternion::IDENTITY);
  225. return m_actors.create(actor);
  226. }
  227. //-----------------------------------------------------------------------------
  228. void PhysicsWorld::destroy_actor(ActorId id)
  229. {
  230. CE_ASSERT(m_actors.has(id), "Actor does not exist");
  231. CE_DELETE(m_actors_pool, m_actors.lookup(id));
  232. m_actors.destroy(id);
  233. }
  234. //-----------------------------------------------------------------------------
  235. ControllerId PhysicsWorld::create_controller(const PhysicsResource* pr, SceneGraph& sg, int32_t node)
  236. {
  237. Controller* controller = CE_NEW(m_controllers_pool, Controller)(pr, sg, node, physics_system::s_physics, m_controller_manager);
  238. return m_controllers.create(controller);
  239. }
  240. //-----------------------------------------------------------------------------
  241. void PhysicsWorld::destroy_controller(ControllerId id)
  242. {
  243. CE_ASSERT(m_controllers.has(id), "Controller does not exist");
  244. CE_DELETE(m_controllers_pool, m_controllers.lookup(id));
  245. m_controllers.destroy(id);
  246. }
  247. //-----------------------------------------------------------------------------
  248. TriggerId PhysicsWorld::create_trigger(const Vector3& half_extents, const Vector3& pos, const Quaternion& rot)
  249. {
  250. Trigger* trigger = CE_NEW(m_triggers_pool, Trigger)(physics_system::s_physics, m_scene, half_extents, pos, rot);
  251. return m_triggers.create(trigger);
  252. }
  253. //-----------------------------------------------------------------------------
  254. void PhysicsWorld::destroy_trigger(TriggerId id)
  255. {
  256. CE_ASSERT(m_triggers.has(id), "Trigger does not exist");
  257. CE_DELETE(m_triggers_pool, m_triggers.lookup(id));
  258. m_triggers.destroy(id);
  259. }
  260. //-----------------------------------------------------------------------------
  261. JointId PhysicsWorld::create_joint(const PhysicsResource* pr, const uint32_t index, const Actor& actor_0, const Actor& actor_1)
  262. {
  263. Joint* joint = CE_NEW(m_joints_pool, Joint)(physics_system::s_physics, pr, index, actor_0, actor_1);
  264. return m_joints.create(joint);
  265. }
  266. //-----------------------------------------------------------------------------
  267. void PhysicsWorld::destroy_joint(JointId id)
  268. {
  269. CE_ASSERT(m_joints.has(id), "Joint does not exist");
  270. CE_DELETE(m_joints_pool, m_joints.lookup(id));
  271. m_joints.destroy(id);
  272. }
  273. //-----------------------------------------------------------------------------
  274. Actor* PhysicsWorld::lookup_actor(StringId32 name)
  275. {
  276. for (uint32_t i = 0; i < m_actors.size(); i++)
  277. {
  278. Actor* actor = m_actors[i];
  279. if (actor->name() == name)
  280. {
  281. return actor;
  282. }
  283. }
  284. }
  285. //-----------------------------------------------------------------------------
  286. Actor* PhysicsWorld::lookup_actor(ActorId id)
  287. {
  288. CE_ASSERT(m_actors.has(id), "Actor does not exist");
  289. return m_actors.lookup(id);
  290. }
  291. //-----------------------------------------------------------------------------
  292. Controller* PhysicsWorld::lookup_controller(ControllerId id)
  293. {
  294. CE_ASSERT(m_controllers.has(id), "Controller does not exist");
  295. return m_controllers.lookup(id);
  296. }
  297. //-----------------------------------------------------------------------------
  298. Trigger* PhysicsWorld::lookup_trigger(TriggerId id)
  299. {
  300. CE_ASSERT(m_triggers.has(id), "Trigger does not exist");
  301. return m_triggers.lookup(id);
  302. }
  303. //-----------------------------------------------------------------------------
  304. Vector3 PhysicsWorld::gravity() const
  305. {
  306. PxVec3 g = m_scene->getGravity();
  307. return Vector3(g.x, g.y, g.z);
  308. }
  309. //-----------------------------------------------------------------------------
  310. void PhysicsWorld::set_gravity(const Vector3& g)
  311. {
  312. m_scene->setGravity(PxVec3(g.x, g.y, g.z));
  313. }
  314. //-----------------------------------------------------------------------------
  315. void PhysicsWorld::set_kinematic(ActorId id)
  316. {
  317. Actor* actor = lookup_actor(id);
  318. actor->set_kinematic();
  319. }
  320. //-----------------------------------------------------------------------------
  321. void PhysicsWorld::clear_kinematic(ActorId id)
  322. {
  323. Actor* actor = lookup_actor(id);
  324. actor->clear_kinematic();
  325. }
  326. //-----------------------------------------------------------------------------
  327. Raycast* PhysicsWorld::make_raycast(RaycastMode::Enum mode, RaycastFilter::Enum filter)
  328. {
  329. return CE_NEW(default_allocator(), Raycast)(m_scene, mode, filter);
  330. }
  331. //-----------------------------------------------------------------------------
  332. void PhysicsWorld::update(float dt)
  333. {
  334. // Run with fixed timestep
  335. m_scene->simulate(1.0 / 60.0);
  336. while (!m_scene->fetchResults());
  337. // Update transforms
  338. PxU32 num_active_transforms;
  339. const PxActiveTransform* active_transforms = m_scene->getActiveTransforms(num_active_transforms);
  340. // Update each actor with its new transform
  341. for (PxU32 i = 0; i < num_active_transforms; i++)
  342. {
  343. // Actors with userData == NULL are controllers
  344. if (active_transforms[i].userData == NULL) continue;
  345. const PxTransform tr = active_transforms[i].actor2World;
  346. const Vector3 pos(tr.p.x, tr.p.y, tr.p.z);
  347. const Quaternion rot(tr.q.x, tr.q.y, tr.q.z, tr.q.w);
  348. static_cast<Actor*>(active_transforms[i].userData)->update(Matrix4x4(rot, pos));
  349. }
  350. // Update controllers
  351. for (uint32_t i = 0; i < m_controllers.size(); i++)
  352. {
  353. m_controllers[i]->update();
  354. }
  355. }
  356. } // namespace crown