BsPhysX.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. #include "BsPhysX.h"
  2. #include "PxPhysicsAPI.h"
  3. #include "BsPhysXMaterial.h"
  4. #include "BsPhysXRigidbody.h"
  5. #include "BsPhysXBoxCollider.h"
  6. #include "BsPhysXSphereCollider.h"
  7. #include "BsPhysXPlaneCollider.h"
  8. #include "BsPhysXCapsuleCollider.h"
  9. #include "BsTaskScheduler.h"
  10. #include "BsTime.h"
  11. #include "Bsvector3.h"
  12. using namespace physx;
  13. namespace BansheeEngine
  14. {
  15. struct PHYSICS_INIT_DESC
  16. {
  17. float typicalLength = 1.0f;
  18. float typicalSpeed = 9.81f;
  19. Vector3 gravity = Vector3(0.0f, -9.81f, 0.0f);
  20. bool initCooking = false;
  21. float timeStep = 1.0f / 60.0f;
  22. };
  23. class PhysXAllocator : public PxAllocatorCallback
  24. {
  25. public:
  26. void* allocate(size_t size, const char*, const char*, int) override
  27. {
  28. void* ptr = bs_alloc_aligned16((UINT32)size);
  29. PX_ASSERT((reinterpret_cast<size_t>(ptr) & 15) == 0);
  30. return ptr;
  31. }
  32. void deallocate(void* ptr) override
  33. {
  34. bs_free_aligned16(ptr);
  35. }
  36. };
  37. class PhysXErrorCallback : public PxErrorCallback
  38. {
  39. public:
  40. void reportError(PxErrorCode::Enum code, const char* message, const char* file, int line) override
  41. {
  42. {
  43. const char* errorCode = nullptr;
  44. UINT32 severity = 0;
  45. switch (code)
  46. {
  47. case PxErrorCode::eNO_ERROR:
  48. errorCode = "No error";
  49. break;
  50. case PxErrorCode::eINVALID_PARAMETER:
  51. errorCode = "Invalid parameter";
  52. severity = 2;
  53. break;
  54. case PxErrorCode::eINVALID_OPERATION:
  55. errorCode = "Invalid operation";
  56. severity = 2;
  57. break;
  58. case PxErrorCode::eOUT_OF_MEMORY:
  59. errorCode = "Out of memory";
  60. severity = 2;
  61. break;
  62. case PxErrorCode::eDEBUG_INFO:
  63. errorCode = "Info";
  64. break;
  65. case PxErrorCode::eDEBUG_WARNING:
  66. errorCode = "Warning";
  67. severity = 1;
  68. break;
  69. case PxErrorCode::ePERF_WARNING:
  70. errorCode = "Performance warning";
  71. severity = 1;
  72. break;
  73. case PxErrorCode::eABORT:
  74. errorCode = "Abort";
  75. severity = 2;
  76. break;
  77. case PxErrorCode::eINTERNAL_ERROR:
  78. errorCode = "Internal error";
  79. severity = 2;
  80. break;
  81. case PxErrorCode::eMASK_ALL:
  82. default:
  83. errorCode = "Unknown error";
  84. severity = 2;
  85. break;
  86. }
  87. StringStream ss;
  88. switch(severity)
  89. {
  90. case 0:
  91. ss << "PhysX info (" << errorCode << "): " << message << " at " << file << ":" << line;
  92. LOGDBG(ss.str());
  93. break;
  94. case 1:
  95. ss << "PhysX warning (" << errorCode << "): " << message << " at " << file << ":" << line;
  96. LOGWRN(ss.str());
  97. break;
  98. case 2:
  99. ss << "PhysX error (" << errorCode << "): " << message << " at " << file << ":" << line;
  100. LOGERR(ss.str());
  101. BS_ASSERT(false); // Halt execution on debug builds when error occurrs
  102. break;
  103. }
  104. }
  105. }
  106. };
  107. class PhysXEventCallback : public PxSimulationEventCallback
  108. {
  109. void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) override { /* Do nothing */ }
  110. void onWake(PxActor** actors, PxU32 count) override { /* Do nothing */ }
  111. void onSleep(PxActor** actors, PxU32 count) override { /* Do nothing */ }
  112. void onTrigger(PxTriggerPair* pairs, PxU32 count) override
  113. {
  114. for (PxU32 i = 0; i < count; i++)
  115. {
  116. const PxTriggerPair& pair = pairs[i];
  117. PhysX::ContactEventType type;
  118. bool ignoreContact = false;
  119. switch ((UINT32)pair.status)
  120. {
  121. case PxPairFlag::eNOTIFY_TOUCH_FOUND:
  122. type = PhysX::ContactEventType::ContactBegin;
  123. break;
  124. case PxPairFlag::eNOTIFY_TOUCH_PERSISTS:
  125. type = PhysX::ContactEventType::ContactStay;
  126. break;
  127. case PxPairFlag::eNOTIFY_TOUCH_LOST:
  128. type = PhysX::ContactEventType::ContactEnd;
  129. break;
  130. default:
  131. ignoreContact = true;
  132. break;
  133. }
  134. if (ignoreContact)
  135. continue;
  136. PhysX::TriggerEvent event;
  137. event.trigger = (Collider*)pair.triggerShape->userData;
  138. event.other = (Collider*)pair.otherShape->userData;
  139. event.type = type;
  140. gPhysX()._reportTriggerEvent(event);
  141. }
  142. }
  143. void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 count) override
  144. {
  145. for (PxU32 i = 0; i < count; i++)
  146. {
  147. const PxContactPair& pair = pairs[i];
  148. PhysX::ContactEventType type;
  149. bool ignoreContact = false;
  150. switch((UINT32)pair.events)
  151. {
  152. case PxPairFlag::eNOTIFY_TOUCH_FOUND:
  153. type = PhysX::ContactEventType::ContactBegin;
  154. break;
  155. case PxPairFlag::eNOTIFY_TOUCH_PERSISTS:
  156. type = PhysX::ContactEventType::ContactStay;
  157. break;
  158. case PxPairFlag::eNOTIFY_TOUCH_LOST:
  159. type = PhysX::ContactEventType::ContactEnd;
  160. break;
  161. default:
  162. ignoreContact = true;
  163. break;
  164. }
  165. if (ignoreContact)
  166. continue;
  167. PhysX::ContactEvent event;
  168. event.colliderA = (Collider*)pair.shapes[0]->userData;
  169. event.colliderB = (Collider*)pair.shapes[1]->userData;
  170. event.type = type;
  171. PxU32 contactCount = pair.contactCount;
  172. const PxU8* stream = pair.contactStream;
  173. PxU16 streamSize = pair.contactStreamSize;
  174. if (contactCount > 0 && streamSize > 0)
  175. {
  176. PxU32 contactIdx = 0;
  177. PxContactStreamIterator iter((PxU8*)stream, streamSize);
  178. stream += ((streamSize + 15) & ~15);
  179. const PxReal* impulses = reinterpret_cast<const PxReal*>(stream);
  180. PxU32 hasImpulses = (pair.flags & PxContactPairFlag::eINTERNAL_HAS_IMPULSES);
  181. while (iter.hasNextPatch())
  182. {
  183. iter.nextPatch();
  184. while (iter.hasNextContact())
  185. {
  186. iter.nextContact();
  187. ContactPoint point;
  188. point.position = fromPxVector(iter.getContactPoint());
  189. point.separation = iter.getSeparation();
  190. point.normal = fromPxVector(iter.getContactNormal());
  191. if (hasImpulses)
  192. point.impulse = impulses[contactIdx];
  193. else
  194. point.impulse = 0.0f;
  195. event.points.push_back(point);
  196. contactIdx++;
  197. }
  198. }
  199. }
  200. gPhysX()._reportContactEvent(event);
  201. }
  202. }
  203. };
  204. class PhysXCPUDispatcher : public PxCpuDispatcher
  205. {
  206. public:
  207. void submitTask(PxBaseTask& physxTask) override
  208. {
  209. // Note: Banshee's task scheduler is pretty low granularity. Consider a better task manager in case PhysX ends
  210. // up submitting many tasks.
  211. // - PhysX's task manager doesn't seem much lighter either. But perhaps I can at least create a task pool to
  212. // avoid allocating them constantly.
  213. auto runTask = [&]() { physxTask.run(); physxTask.release(); };
  214. TaskPtr task = Task::create("PhysX", runTask);
  215. TaskScheduler::instance().addTask(task);
  216. }
  217. PxU32 getWorkerCount() const override
  218. {
  219. return (PxU32)TaskScheduler::instance().getNumWorkers();
  220. }
  221. };
  222. PxFilterFlags PhysXFilterShader(PxFilterObjectAttributes attr0, PxFilterData data0, PxFilterObjectAttributes attr1,
  223. PxFilterData data1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize)
  224. {
  225. if (PxFilterObjectIsTrigger(attr0) || PxFilterObjectIsTrigger(attr1))
  226. {
  227. pairFlags = PxPairFlag::eTRIGGER_DEFAULT;
  228. return PxFilterFlags();
  229. }
  230. UINT64 groupA = *(UINT64*)&data0.word0;
  231. UINT64 groupB = *(UINT64*)&data1.word0;
  232. bool canCollide = gPhysics().isCollisionEnabled(groupA, groupB);
  233. if (!canCollide)
  234. return PxFilterFlag::eSUPPRESS;
  235. pairFlags = PxPairFlag::eCONTACT_DEFAULT;
  236. return PxFilterFlags();
  237. }
  238. static PhysXAllocator gPhysXAllocator;
  239. static PhysXErrorCallback gPhysXErrorHandler;
  240. static PhysXCPUDispatcher gPhysXCPUDispatcher;
  241. static PhysXEventCallback gPhysXEventCallback;
  242. PhysX::PhysX()
  243. {
  244. PHYSICS_INIT_DESC input; // TODO - Make this an input parameter.
  245. PxTolerancesScale scale;
  246. scale.length = input.typicalLength;
  247. scale.speed = input.typicalSpeed;
  248. mFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gPhysXAllocator, gPhysXErrorHandler);
  249. mPhysics = PxCreateBasePhysics(PX_PHYSICS_VERSION, *mFoundation, scale);
  250. PxRegisterArticulations(*mPhysics);
  251. if (input.initCooking)
  252. {
  253. PxCookingParams cookingParams(scale); // TODO - Potentially allow more customization to set up cooking params
  254. mCooking = PxCreateCooking(PX_PHYSICS_VERSION, *mFoundation, cookingParams);
  255. }
  256. PxSceneDesc sceneDesc(scale); // TODO - Test out various other parameters provided by scene desc
  257. sceneDesc.gravity = toPxVector(input.gravity);
  258. sceneDesc.cpuDispatcher = &gPhysXCPUDispatcher;
  259. sceneDesc.filterShader = PhysXFilterShader;
  260. sceneDesc.simulationEventCallback = &gPhysXEventCallback;
  261. mScene = mPhysics->createScene(sceneDesc);
  262. mSimulationStep = input.timeStep;
  263. mDefaultMaterial = mPhysics->createMaterial(0.0f, 0.0f, 0.0f);
  264. }
  265. PhysX::~PhysX()
  266. {
  267. mScene->release();
  268. if (mCooking != nullptr)
  269. mCooking->release();
  270. mPhysics->release();
  271. mFoundation->release();
  272. }
  273. void PhysX::update()
  274. {
  275. float nextFrameTime = mLastSimulationTime + mSimulationStep;
  276. float curFrameTime = gTime().getTime();
  277. if(curFrameTime < nextFrameTime)
  278. {
  279. // TODO - Interpolate rigidbodies but perform no actual simulation
  280. return;
  281. }
  282. float simulationAmount = curFrameTime - mLastSimulationTime;
  283. while (simulationAmount >= mSimulationStep) // In case we're running really slow multiple updates might be needed
  284. {
  285. // TODO - Consider delaying fetchResults one frame. This could improve performance but at a cost to input latency.
  286. // TODO - Provide a scratch buffer for the simulation (use the frame allocator, but I must extend it so it allocates
  287. // on a 16 byte boundary).
  288. mScene->simulate(mSimulationStep);
  289. mScene->fetchResults(true);
  290. // TODO - Update all rigidbody transfroms from their PhsyX state
  291. simulationAmount -= mSimulationStep;
  292. }
  293. // TODO - Consider extrapolating for the remaining "simulationAmount" value
  294. mLastSimulationTime = curFrameTime;
  295. triggerEvents();
  296. }
  297. void PhysX::_reportContactEvent(const ContactEvent& event)
  298. {
  299. mContactEvents.push_back(event);
  300. }
  301. void PhysX::_reportTriggerEvent(const TriggerEvent& event)
  302. {
  303. mTriggerEvents.push_back(event);
  304. }
  305. void PhysX::triggerEvents()
  306. {
  307. CollisionData data;
  308. for(auto& entry : mTriggerEvents)
  309. {
  310. data.collider = entry.other;
  311. switch (entry.type)
  312. {
  313. case ContactEventType::ContactBegin:
  314. entry.trigger->onCollisionBegin(data);
  315. break;
  316. case ContactEventType::ContactStay:
  317. entry.trigger->onCollisionStay(data);
  318. break;
  319. case ContactEventType::ContactEnd:
  320. entry.trigger->onCollisionEnd(data);
  321. break;
  322. }
  323. }
  324. auto notifyContact = [&](Collider* obj, Collider* other, ContactEventType type,
  325. const Vector<ContactPoint>& points, bool flipNormals = false)
  326. {
  327. data.collider = other;
  328. data.contactPoints = points;
  329. if(flipNormals)
  330. {
  331. for (auto& point : data.contactPoints)
  332. point.normal = -point.normal;
  333. }
  334. SPtr<Rigidbody> rigidbody = obj->getRigidbody();
  335. if(rigidbody != nullptr)
  336. {
  337. switch (type)
  338. {
  339. case ContactEventType::ContactBegin:
  340. rigidbody->onCollisionBegin(data);
  341. break;
  342. case ContactEventType::ContactStay:
  343. rigidbody->onCollisionStay(data);
  344. break;
  345. case ContactEventType::ContactEnd:
  346. rigidbody->onCollisionEnd(data);
  347. break;
  348. }
  349. }
  350. else
  351. {
  352. switch (type)
  353. {
  354. case ContactEventType::ContactBegin:
  355. obj->onCollisionBegin(data);
  356. break;
  357. case ContactEventType::ContactStay:
  358. obj->onCollisionStay(data);
  359. break;
  360. case ContactEventType::ContactEnd:
  361. obj->onCollisionEnd(data);
  362. break;
  363. }
  364. }
  365. };
  366. for (auto& entry : mContactEvents)
  367. {
  368. notifyContact(entry.colliderA, entry.colliderB, entry.type, entry.points, true);
  369. notifyContact(entry.colliderB, entry.colliderA, entry.type, entry.points, false);
  370. }
  371. mTriggerEvents.clear();
  372. mContactEvents.clear();
  373. }
  374. SPtr<PhysicsMaterial> PhysX::createMaterial(float staticFriction, float dynamicFriction, float restitution)
  375. {
  376. return bs_shared_ptr_new<PhysXMaterial>(mPhysics, staticFriction, dynamicFriction, restitution);
  377. }
  378. SPtr<Rigidbody> PhysX::createRigidbody(const Vector3& position, const Quaternion& rotation, UINT32 priority)
  379. {
  380. return bs_shared_ptr_new<PhysXRigidbody>(mPhysics, mScene, position, rotation, priority);
  381. }
  382. SPtr<BoxCollider> PhysX::createBoxCollider(float extentX, float extentY, float extentZ, const Vector3& position,
  383. const Quaternion& rotation)
  384. {
  385. return bs_shared_ptr_new<PhysXBoxCollider>(mPhysics, position, rotation, extentX, extentY, extentZ);
  386. }
  387. SPtr<SphereCollider> PhysX::createSphereCollider(float radius, const Vector3& position, const Quaternion& rotation)
  388. {
  389. return bs_shared_ptr_new<PhysXSphereCollider>(mPhysics, position, rotation, radius);
  390. }
  391. SPtr<PlaneCollider> PhysX::createPlaneCollider(const Vector3& position, const Quaternion& rotation)
  392. {
  393. return bs_shared_ptr_new<PhysXPlaneCollider>(mPhysics, position, rotation);
  394. }
  395. SPtr<CapsuleCollider> PhysX::createCapsuleCollider(float radius, float halfHeight, const Vector3& position,
  396. const Quaternion& rotation)
  397. {
  398. return bs_shared_ptr_new<PhysXCapsuleCollider>(mPhysics, position, rotation, radius, halfHeight);
  399. }
  400. PhysX& gPhysX()
  401. {
  402. return static_cast<PhysX&>(PhysX::instance());
  403. }
  404. }