physics_world.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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 "physics_world.h"
  24. #include "vector3.h"
  25. #include "actor.h"
  26. #include "device.h"
  27. #include "quaternion.h"
  28. #include "scene_graph.h"
  29. #include "controller.h"
  30. #include "joint.h"
  31. #include "physics_callback.h"
  32. #include "proxy_allocator.h"
  33. #include "string_utils.h"
  34. #include "string_utils.h"
  35. #include "actor.h"
  36. #include "resource_manager.h"
  37. #include "raycast.h"
  38. #include "unit.h"
  39. #include "config.h"
  40. #include "world.h"
  41. #include "debug_line.h"
  42. #include "color4.h"
  43. #include "int_setting.h"
  44. #include "physics.h"
  45. #include "PxPhysicsAPI.h"
  46. using physx::PxSceneDesc;
  47. using physx::PxVec3;
  48. using physx::PxTransform;
  49. using physx::PxQuat;
  50. using physx::PxHalfPi;
  51. using physx::PxPlaneGeometry;
  52. using physx::PxMaterial;
  53. using physx::PxShape;
  54. using physx::PxRigidStatic;
  55. using physx::PxActiveTransform;
  56. using physx::PxU32;
  57. using physx::PxSceneFlag;
  58. using physx::PxFilterFlags;
  59. using physx::PxFilterData;
  60. using physx::PxPairFlags;
  61. using physx::PxFilterObjectAttributes;
  62. using physx::PxFilterObjectIsTrigger;
  63. using physx::PxPairFlag;
  64. using physx::PxFilterFlag;
  65. using physx::PxSceneLimits;
  66. using physx::PxVisualizationParameter;
  67. using physx::PxSphereGeometry;
  68. using physx::PxCapsuleGeometry;
  69. using physx::PxBoxGeometry;
  70. using physx::PxRenderBuffer;
  71. using physx::PxDebugLine;
  72. namespace crown
  73. {
  74. static IntSetting g_physics_debug("physics.debug", "Enable physics debug rendering.", 0, 0, 1);
  75. namespace physics_globals
  76. {
  77. using physx::PxFoundation;
  78. using physx::PxPhysics;
  79. using physx::PxCooking;
  80. using physx::PxCookingParams;
  81. using physx::PxTolerancesScale;
  82. using physx::PxAllocatorCallback;
  83. using physx::PxErrorCallback;
  84. using physx::PxErrorCode;
  85. class PhysXAllocator : public PxAllocatorCallback
  86. {
  87. public:
  88. PhysXAllocator()
  89. : m_backing("physics", default_allocator())
  90. {
  91. }
  92. void* allocate(size_t size, const char*, const char*, int)
  93. {
  94. return m_backing.allocate(size, 16);
  95. }
  96. void deallocate(void* p)
  97. {
  98. m_backing.deallocate(p);
  99. }
  100. private:
  101. ProxyAllocator m_backing;
  102. };
  103. class PhysXError : public PxErrorCallback
  104. {
  105. public:
  106. void reportError(PxErrorCode::Enum code, const char* message, const char* /*file*/, int /*line*/)
  107. {
  108. switch (code)
  109. {
  110. case PxErrorCode::eDEBUG_INFO:
  111. {
  112. CE_LOGI("PhysX: %s", message);
  113. break;
  114. }
  115. case PxErrorCode::eDEBUG_WARNING:
  116. case PxErrorCode::ePERF_WARNING:
  117. {
  118. CE_LOGW("PhysX: %s", message);
  119. break;
  120. }
  121. case PxErrorCode::eINVALID_PARAMETER:
  122. case PxErrorCode::eINVALID_OPERATION:
  123. case PxErrorCode::eOUT_OF_MEMORY:
  124. case PxErrorCode::eINTERNAL_ERROR:
  125. case PxErrorCode::eABORT:
  126. {
  127. CE_ASSERT(false, "PhysX: %s", message);
  128. break;
  129. }
  130. default:
  131. {
  132. CE_FATAL("Oops, unknown physx error");
  133. break;
  134. }
  135. }
  136. }
  137. };
  138. PxFilterFlags FilterShader(PxFilterObjectAttributes attributes0, PxFilterData filterData0,
  139. PxFilterObjectAttributes attributes1, PxFilterData filterData1,
  140. PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize)
  141. {
  142. // let triggers through
  143. if(PxFilterObjectIsTrigger(attributes0) || PxFilterObjectIsTrigger(attributes1))
  144. {
  145. pairFlags = PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_TOUCH_LOST;
  146. return PxFilterFlag::eDEFAULT;
  147. }
  148. // trigger the contact callback for pairs (A,B) where
  149. // the filtermask of A contains the ID of B and vice versa.
  150. if((filterData0.word0 & filterData1.word1) && (filterData1.word0 & filterData0.word1))
  151. {
  152. pairFlags |= PxPairFlag::eCONTACT_DEFAULT
  153. | PxPairFlag::eNOTIFY_TOUCH_FOUND
  154. | PxPairFlag::eNOTIFY_TOUCH_LOST
  155. | PxPairFlag::eNOTIFY_CONTACT_POINTS;
  156. return PxFilterFlag::eDEFAULT;
  157. }
  158. return PxFilterFlag::eSUPPRESS;
  159. }
  160. // Global PhysX objects
  161. static PhysXAllocator* s_px_allocator;
  162. static PhysXError* s_px_error;
  163. static PxFoundation* s_foundation;
  164. static PxPhysics* s_physics;
  165. static PxCooking* s_cooking;
  166. void init()
  167. {
  168. s_px_allocator = CE_NEW(default_allocator(), PhysXAllocator)();
  169. s_px_error = CE_NEW(default_allocator(), PhysXError)();
  170. s_foundation = PxCreateFoundation(PX_PHYSICS_VERSION, *s_px_allocator, *s_px_error);
  171. CE_ASSERT(s_foundation, "Unable to create PhysX Foundation");
  172. s_physics = PxCreatePhysics(PX_PHYSICS_VERSION, *s_foundation, physx::PxTolerancesScale());
  173. CE_ASSERT(s_physics, "Unable to create PhysX Physics");
  174. bool extension = PxInitExtensions(*s_physics);
  175. CE_ASSERT(extension, "Unable to initialize PhysX Extensions");
  176. CE_UNUSED(extension);
  177. s_cooking = PxCreateCooking(PX_PHYSICS_VERSION, *s_foundation, PxCookingParams(PxTolerancesScale()));
  178. CE_ASSERT(s_cooking, "Unable to create PhysX Cooking");
  179. }
  180. void shutdown()
  181. {
  182. PxCloseExtensions();
  183. s_cooking->release();
  184. s_physics->release();
  185. s_foundation->release();
  186. CE_DELETE(default_allocator(), s_px_error);
  187. CE_DELETE(default_allocator(), s_px_allocator);
  188. }
  189. #if defined(CROWN_DEBUG)
  190. void draw_debug_lines(PxScene* scene, DebugLine& line)
  191. {
  192. const PxRenderBuffer& rb = scene->getRenderBuffer();
  193. for(PxU32 i = 0; i < rb.getNbLines(); i++)
  194. {
  195. const PxDebugLine& pxline = rb.getLines()[i];
  196. line.add_line(Vector3(pxline.pos0.x, pxline.pos0.y, pxline.pos0.z),
  197. Vector3(pxline.pos1.x, pxline.pos1.y, pxline.pos1.z),
  198. Color4(pxline.color0));
  199. }
  200. line.commit();
  201. line.clear();
  202. }
  203. #endif
  204. } // namespace physics_globals
  205. PhysicsWorld::PhysicsWorld(World& world)
  206. : m_world(world)
  207. , m_scene(NULL)
  208. , m_buffer(m_hits, 64)
  209. , m_actors_pool(default_allocator(), CE_MAX_ACTORS, sizeof(Actor), CE_ALIGNOF(Actor))
  210. , m_controllers_pool(default_allocator(), CE_MAX_CONTROLLERS, sizeof(Controller), CE_ALIGNOF(Controller))
  211. , m_joints_pool(default_allocator(), CE_MAX_JOINTS, sizeof(Joint), CE_ALIGNOF(Joint))
  212. , m_raycasts_pool(default_allocator(), CE_MAX_RAYCASTS, sizeof(Raycast), CE_ALIGNOF(Raycast))
  213. , m_events(default_allocator())
  214. , m_callback(m_events)
  215. #if defined(CROWN_DEBUG)
  216. , m_debug_line(NULL)
  217. #endif
  218. {
  219. // Create the scene
  220. PxSceneLimits scene_limits;
  221. scene_limits.maxNbActors = CE_MAX_ACTORS;
  222. CE_ASSERT(scene_limits.isValid(), "Scene limits is not valid");
  223. PxSceneDesc scene_desc(physics_globals::s_physics->getTolerancesScale());
  224. scene_desc.gravity = PxVec3(0.0f, -9.81f, 0.0f);
  225. scene_desc.limits = scene_limits;
  226. scene_desc.filterShader = physics_globals::FilterShader;
  227. scene_desc.simulationEventCallback = &m_callback;
  228. scene_desc.flags = PxSceneFlag::eENABLE_ACTIVETRANSFORMS
  229. | PxSceneFlag::eENABLE_KINEMATIC_STATIC_PAIRS
  230. | PxSceneFlag::eENABLE_KINEMATIC_PAIRS;
  231. if(!scene_desc.cpuDispatcher)
  232. {
  233. m_cpu_dispatcher = physx::PxDefaultCpuDispatcherCreate(1);
  234. CE_ASSERT(m_cpu_dispatcher != NULL, "Failed to create PhysX cpu dispatcher");
  235. scene_desc.cpuDispatcher = m_cpu_dispatcher;
  236. }
  237. CE_ASSERT(scene_desc.isValid(), "Scene is not valid");
  238. m_scene = physics_globals::s_physics->createScene(scene_desc);
  239. // Create controller manager
  240. m_controller_manager = PxCreateControllerManager(*m_scene);
  241. CE_ASSERT(m_controller_manager != NULL, "Failed to create PhysX controller manager");
  242. m_resource = (PhysicsConfigResource*) device()->resource_manager()->get("physics_config", "global");
  243. #if defined(CROWN_DEBUG)
  244. m_scene->setVisualizationParameter(PxVisualizationParameter::eSCALE, 1);
  245. m_scene->setVisualizationParameter(PxVisualizationParameter::eACTOR_AXES, 1);
  246. m_scene->setVisualizationParameter(PxVisualizationParameter::eCOLLISION_SHAPES, 1);
  247. m_debug_line = world.create_debug_line(false);
  248. #endif
  249. }
  250. PhysicsWorld::~PhysicsWorld()
  251. {
  252. m_cpu_dispatcher->release();
  253. m_controller_manager->release();
  254. m_scene->release();
  255. #if defined(CROWN_DEBUG)
  256. m_world.destroy_debug_line(m_debug_line);
  257. #endif
  258. }
  259. ActorId PhysicsWorld::create_actor(const PhysicsResource* res, const uint32_t index, SceneGraph& sg, int32_t node, UnitId unit_id)
  260. {
  261. Actor* actor = CE_NEW(m_actors_pool, Actor)(*this, res, index, sg, node, unit_id);
  262. return id_array::create(m_actors, actor);
  263. }
  264. void PhysicsWorld::destroy_actor(ActorId id)
  265. {
  266. CE_DELETE(m_actors_pool, id_array::get(m_actors, id));
  267. id_array::destroy(m_actors, id);
  268. }
  269. ControllerId PhysicsWorld::create_controller(const PhysicsResource* pr, SceneGraph& sg, int32_t node)
  270. {
  271. Controller* controller = CE_NEW(m_controllers_pool, Controller)(pr, sg, node, physics_globals::s_physics, m_controller_manager);
  272. return id_array::create(m_controllers, controller);
  273. }
  274. void PhysicsWorld::destroy_controller(ControllerId id)
  275. {
  276. CE_DELETE(m_controllers_pool, id_array::get(m_controllers, id));
  277. id_array::destroy(m_controllers, id);
  278. }
  279. JointId PhysicsWorld::create_joint(const PhysicsResource* pr, const uint32_t index, const Actor& actor_0, const Actor& actor_1)
  280. {
  281. Joint* joint = CE_NEW(m_joints_pool, Joint)(physics_globals::s_physics, pr, index, actor_0, actor_1);
  282. return id_array::create(m_joints, joint);
  283. }
  284. void PhysicsWorld::destroy_joint(JointId id)
  285. {
  286. CE_DELETE(m_joints_pool, id_array::get(m_joints, id));
  287. id_array::destroy(m_joints, id);
  288. }
  289. RaycastId PhysicsWorld::create_raycast(CollisionMode::Enum mode, CollisionType::Enum filter)
  290. {
  291. Raycast* raycast = CE_NEW(m_raycasts_pool, Raycast)(m_scene, mode, filter);
  292. return id_array::create(m_raycasts, raycast);
  293. }
  294. void PhysicsWorld::destroy_raycast(RaycastId id)
  295. {
  296. CE_DELETE(m_raycasts_pool, id_array::get(m_raycasts, id));
  297. id_array::destroy(m_raycasts, id);
  298. }
  299. Actor* PhysicsWorld::get_actor(ActorId id)
  300. {
  301. return id_array::get(m_actors, id);
  302. }
  303. Controller* PhysicsWorld::get_controller(ControllerId id)
  304. {
  305. return id_array::get(m_controllers, id);
  306. }
  307. Raycast* PhysicsWorld::get_raycast(RaycastId id)
  308. {
  309. return id_array::get(m_raycasts, id);
  310. }
  311. Vector3 PhysicsWorld::gravity() const
  312. {
  313. PxVec3 g = m_scene->getGravity();
  314. return Vector3(g.x, g.y, g.z);
  315. }
  316. void PhysicsWorld::set_gravity(const Vector3& g)
  317. {
  318. m_scene->setGravity(PxVec3(g.x, g.y, g.z));
  319. }
  320. void PhysicsWorld::overlap_test(CollisionType::Enum filter, ShapeType::Enum type,
  321. const Vector3& pos, const Quaternion& rot, const Vector3& size, Array<Actor*>& actors)
  322. {
  323. PxTransform transform(PxVec3(pos.x, pos.y, pos.z), PxQuat(rot.x, rot.y, rot.z, rot.w));
  324. switch(type)
  325. {
  326. case ShapeType::SPHERE:
  327. {
  328. PxSphereGeometry geometry(size.x);
  329. m_scene->overlap(geometry, transform, m_buffer);
  330. break;
  331. }
  332. case ShapeType::CAPSULE:
  333. {
  334. PxCapsuleGeometry geometry(size.x, size.y);
  335. m_scene->overlap(geometry, transform, m_buffer);
  336. break;
  337. }
  338. case ShapeType::BOX:
  339. {
  340. PxBoxGeometry geometry(size.x, size.y, size.z);
  341. m_scene->overlap(geometry, transform, m_buffer);
  342. break;
  343. }
  344. default: CE_FATAL("Only spheres, capsules and boxs are supported in overlap test"); break;
  345. }
  346. for (uint32_t i = 0; i < m_buffer.getNbAnyHits(); i++)
  347. {
  348. PxOverlapHit oh = m_buffer.getAnyHit(i);
  349. array::push_back(actors, (Actor*)(oh.actor->userData));
  350. }
  351. }
  352. void PhysicsWorld::update(float dt)
  353. {
  354. // Run with fixed timestep
  355. m_scene->simulate(1.0 / 60.0);
  356. while (!m_scene->fetchResults());
  357. // Update transforms
  358. PxU32 num_active_transforms;
  359. const PxActiveTransform* active_transforms = m_scene->getActiveTransforms(num_active_transforms);
  360. // Update each actor with its new transform
  361. for (PxU32 i = 0; i < num_active_transforms; i++)
  362. {
  363. // Actors with userData == NULL are controllers
  364. if (active_transforms[i].userData == NULL) continue;
  365. const PxTransform tr = active_transforms[i].actor2World;
  366. const Vector3 pos(tr.p.x, tr.p.y, tr.p.z);
  367. const Quaternion rot(tr.q.x, tr.q.y, tr.q.z, tr.q.w);
  368. static_cast<Actor*>(active_transforms[i].userData)->update(Matrix4x4(rot, pos));
  369. }
  370. // Update controllers
  371. for (uint32_t i = 0; i < id_array::size(m_controllers); i++)
  372. {
  373. m_controllers[i]->update();
  374. }
  375. }
  376. void PhysicsWorld::draw_debug()
  377. {
  378. #if defined(CROWN_DEBUG)
  379. if (g_physics_debug)
  380. physics_globals::draw_debug_lines(m_scene, *m_debug_line);
  381. #endif
  382. }
  383. PxPhysics* PhysicsWorld::physx_physics() { return physics_globals::s_physics; }
  384. PxCooking* PhysicsWorld::physx_cooking() { return physics_globals::s_cooking; }
  385. PxScene* PhysicsWorld::physx_scene() { return m_scene; }
  386. } // namespace crown